PHP: How to instantiate a class with arguments from within another class

Sarfraz picture Sarfraz · Dec 7, 2009 · Viewed 27.5k times · Source

I am in a situations where i need to instantiate a class with arguments from within an instance of another class. Here is the prototype:

//test.php

class test
{
    function __construct($a, $b, $c)
    {
        echo $a . '<br />';
        echo $b . '<br />';
        echo $c . '<br />';
    }
}

Now, i need to instantiate above class using below class's cls function:

class myclass
{
function cls($file_name, $args = array())
{
    include $file_name . ".php";

    if (isset($args))
    {
        // this is where the problem might be, i need to pass as many arguments as test class has.
        $class_instance = new $file_name($args);
    }
    else
    {
        $class_instance = new $file_name();
    }

    return $class_instance;
}
}

Now when i try to create an instance of test class while passing arguments to it:

$myclass = new myclass;
$test = $myclass->cls('test', array('a1', 'b2', 'c3'));

It gives error: Missing argument 1 and 2; only first argument is passed.

This works fine if i instantiate a class which has no arguments in it's constructor function.

For experienced PHP developers, above should not be much of a problem. Please help.

Thanks

Answer

user187291 picture user187291 · Dec 7, 2009

you need Reflection http://php.net/manual/en/class.reflectionclass.php

if(count($args) == 0)
   $obj = new $className;
else {
   $r = new ReflectionClass($className);
   $obj = $r->newInstanceArgs($args);
}