我有一些使用动态类(即来自变量)创建广告实例的代码:
$instance = new $myClass();
由于构造函数根据$myClass值具有不同的参数计数,如何将变量参数列表传递给新语句?可能吗?
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
        )
)
*/
我不知道为什么,但我不喜欢在我的代码中使用 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 而不是 new 的静态调用
echo ClassName::init('arg1', 'arg2', 'arg3')->method1()->method2();
使用 initArray 而不是 new 的静态调用
echo ClassName::initArray(['arg1', 'arg2', 'arg3'])->method1()->method2();
静态方法的好处是您可以在 init 方法中运行一些预构造操作,例如构造函数参数验证。
最简单的方法是使用数组。
public function __construct($args = array())
{
  foreach($array as $k => $v)
  {
    if(property_exists('myClass', $k)) // where myClass is your class name.
    {
      $this->{$k} = $v;
    }
  }
}