可以使用类方法中的类名属性实例化PHP实例(在一行代码中)


Possible to instantiate a PHP instance using a class name property from within a class method (in one line of code)?

我希望能够使用存储在另一个类的属性中的类名来实例化一个类,我希望用一行代码来实现这一点,如下面代码中的注释所示(它应该至少适用于一个最新版本的PHP 5)。这可能吗?

<?php
class Foo {
  public function doFoo() {
    echo "foo'n";
  }
}
class Bar {
  function __construct($className) {
    $this->className = $className;
  }
  public function doBar() {
    //INSTEAD OF THESE TWO LINES...
    //$className = $this->className;
    //$instance = new $className();
    //I WOULD LIKE THIS (OR SOME OTHER) ONE-LINER TO WORK:
    $instance = $this->className();
    $instance->doFoo();
  }
}
$bar = new Bar('Foo');
$bar->doBar();

预期输出:

foo

代码中有一个明显的拼写错误,它调用的是函数而不是构造函数,可以修复如下:

$instance = new $this->className();

这很管用。