Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 267
Sarfraz Avatar asked Dec 07 '09 06:12

Sarfraz


1 Answers

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);
}
like image 77
user187291 Avatar answered Sep 19 '22 06:09

user187291