我有一些代码用动态类(即来自变量)创建广告实例:
$instance = new $myClass();
由于构造函数根据$myClass
值具有不同的参数计数,因此如何将参数的变量列表传递给新语句?有可能吗?
答案 0 :(得分:10)
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
您还可以在上面的代码中检查构造函数:
$constructorRefl = $refl->getMethod( "__construct");
print_r( $constructorRefl->getParameters() );
/*
Array
(
[0] => ReflectionParameter Object
(
[name] => a
)
[1] => ReflectionParameter Object
(
[name] => b
)
[2] => ReflectionParameter Object
(
[name] => c
)
)
*/
答案 1 :(得分:1)
最简单的方法是使用数组。
public function __construct($args = array())
{
foreach($array as $k => $v)
{
if(property_exists('myClass', $k)) // where myClass is your class name.
{
$this->{$k} = $v;
}
}
}
答案 2 :(得分:0)
我不知道为什么,但我不喜欢在我的代码中使用new运算符。
这是一个静态函数,用于创建一个名为静态的类的实例。
class ClassName {
public static function init(){
return (new ReflectionClass(get_called_class()))->newInstanceArgs(func_get_args());
}
public static function initArray($array=[]){
return (new ReflectionClass(get_called_class()))->newInstanceArgs($array);
}
public function __construct($arg1, $arg2, $arg3){
///construction code
}
}
如果你在命名空间中使用它,你需要像这样转义ReflectionClass:new \ ReflectionClass ...
现在你可以使用可变数量的参数调用init()方法,它会将它传递给构造函数并为你返回一个对象。
正常使用新
$obj = new ClassName('arg1', 'arg2', 'arg3');
echo $obj->method1()->method2();
使用新的
的内联方式echo (new ClassName('arg1', 'arg2', 'arg3'))->method1()->method2();
使用init而非新
进行静态调用echo ClassName::init('arg1', 'arg2', 'arg3')->method1()->method2();
使用initArray而不是新
进行静态调用echo ClassName::initArray(['arg1', 'arg2', 'arg3'])->method1()->method2();
静态方法的优点是你可以在init方法中运行一些预构造操作,比如构造函数参数验证。