PHP:如何使用另一个类中的参数实例化一个类

Sar*_*raz 13 php oop class object instantiation

我处于一种情况,我需要在另一个类的实例中实例化一个带有参数的类.这是原型:

//test.php

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

现在,我需要使用下面的类的cls函数来实例化上面的类:

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;
}
}
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试在向其传递参数的同时创建测试类的实例时:

$myclass = new myclass;
$test = $myclass->cls('test', array('a1', 'b2', 'c3'));
Run Code Online (Sandbox Code Playgroud)

它给出错误:缺少参数1和2; 只传递第一个参数.

如果我实例化一个在其构造函数中没有参数的类,这可以正常工作.

对于有经验的PHP开发人员来说,上面应该不是什么大问题.请帮忙.

谢谢

use*_*291 30

你需要反思http://php.net/manual/en/class.reflectionclass.php

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