我有一些代码用动态类(即从变量)创建广告实例:
$instance = new $myClass();
Run Code Online (Sandbox Code Playgroud)
由于构造函数根据$myClass值具有不同的参数计数,因此如何将参数的变量列表传递给新语句?可能吗?
Esa*_*ija 11
class Horse {
public function __construct( $a, $b, $c ) {
echo $a;
echo $b;
echo $c;
}
}
$myClass = "Horse";
$refl = new ReflectionClass($myClass);
$instance = $refl->newInstanceArgs( array(
"first", "second", "third"
));
//"firstsecondthird" is echoed
Run Code Online (Sandbox Code Playgroud)
您还可以在上面的代码中检查构造函数:
$constructorRefl = $refl->getMethod( "__construct");
print_r( $constructorRefl->getParameters() );
/*
Array
(
[0] => ReflectionParameter Object
(
[name] => a
)
[1] => ReflectionParameter Object
(
[name] => b
)
[2] => ReflectionParameter Object
(
[name] => c
)
)
*/
Run Code Online (Sandbox Code Playgroud)