是否有一个call_user_func()等效于创建一个新的类实例?

Ste*_*e H 21 php php4 class

如何创建一个具有给定数组参数的类以发送给构造函数?有点像:

class a {
    var $args = false;
    function a() {$this->args = func_get_args();}
}

$a = call_user_func_array('new a',array(1,2,3));
print_r($a->args);
Run Code Online (Sandbox Code Playgroud)

理想情况下,PHP4和PHP5都需要在不修改类的情况下工作.有任何想法吗?

Vol*_*erK 24

ReflectionClass:newInstance()(或newInstanceArgs())让你这样做.

例如

class Foo {
  public function __construct() {  
    $p = func_get_args();
    echo 'Foo::__construct(', join(',', $p), ') invoked';
  }
}

$rc = new ReflectionClass('Foo');
$foo = $rc->newInstanceArgs( array(1,2,3,4,5) );
Run Code Online (Sandbox Code Playgroud)

编辑:没有ReflectionClass,可能兼容php4(对不起,现在没有php4)

class Foo {
  public function __construct() {  
    $p = func_get_args();
    echo 'Foo::__construct(', join(',', $p), ') invoked';
  }
}

$class = 'Foo';
$rc = new $class(1,2,3,4);
Run Code Online (Sandbox Code Playgroud)

速度比较:由于这里提到的反射速度是一个小的(合成)测试

define('ITERATIONS', 100000);

class Foo {
  protected $something;
  public function __construct() {
    $p = func_get_args();
    $this->something = 'Foo::__construct('.join(',', $p).')';
  }
}

$rcStatic=new ReflectionClass('Foo'); 
$fns = array(
  'direct new'=>function() { $obj = new Foo(1,2,3,4); },
  'indirect new'=>function() { $class='Foo'; $obj = new $class(1,2,3,4); }, 
  'reflection'=>function() { $rc=new ReflectionClass('Foo'); $obj = $rc->newInstanceArgs( array(1,2,3,4) ); },
  'reflection cached'=>function() use ($rcStatic) { $obj = $rcStatic->newInstanceArgs( array(1,2,3,4) ); },
);


sleep(1);
foreach($fns as $name=>$f) {
  $start = microtime(true);
  for($i=0; $i<ITERATIONS; $i++) {
    $f();
  }
  $end = microtime(true);
  echo $name, ': ', $end-$start, "\n";
  sleep(1);
}
Run Code Online (Sandbox Code Playgroud)

它打印在我(不那么快)的笔记本上

direct new: 0.71329689025879
indirect new: 0.75944685935974
reflection: 1.3510940074921
reflection cached: 1.0181720256805
Run Code Online (Sandbox Code Playgroud)

不是那么糟糕,是吗?

  • 使用`new $ class($ args)`方法有什么缺点吗? (2认同)

Gor*_*don 10

查看Factory Method模式并查看此示例

来自维基百科:

工厂方法模式是面向对象的设计模式.与其他创建模式一样,它处理创建对象(产品)的问题,而不指定将要创建的确切对象类.

如果你不想为此使用专用工厂,你仍然可以将Volker的代码包装成一个函数,例如

/**
 * Creates a new object instance
 *
 * This method creates a new object instance from from the passed $className
 * and $arguments. The second param $arguments is optional.
 *
 * @param  String $className class to instantiate
 * @param  Array  $arguments arguments required by $className's constructor
 * @return Mixed  instance of $className
 */
function createInstance($className, array $arguments = array())
{
    if(class_exists($className)) {
        return call_user_func_array(array(
            new ReflectionClass($className), 'newInstance'), 
            $arguments);
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)