PHP 静态工厂方法:动态实例化调用实例 class

PHP static factory method: dynamically instantiate instance of the calling class

这个 PHP 问题与 有关,但有点不同。我有一个名为 create() 的静态工厂方法,它实例化了一个 class 实例。我希望该方法动态实例化调用它的 (sub)class 的实例。所以,它实例化的 class 必须在运行时确定。但是我想这样做而不必在 subclass 中重新定义静态工厂方法(这在我的示例中是完全有效的,因为 subclass 没有要初始化的新数据成员)。这完全可能吗?

class Foo {

  private $name;

  public static function create($name) {

    //HERE INSTED OF:
    return new Foo($name);
    //I WANT SOMETHING LIKE:
    //return new get_class($this)($name);//doesn't work
    //return self($this);//doesn't work either

  }

  private function __construct($name) {

    $this->name = $name;

  }

  public function getName() {

    return $this->name;

  }

}

// the following class has no private data, just extra methods:

class SubFoo extends Foo {

  public function getHelloName() {

    echo "Hello, ", $this->getName(), ".\n";

  }

}


$foo = Foo::create("Joe");
echo $foo->getName(), "\n"; // MUST OUTPUT: Joe

$subFoo = SubFoo::create("Joe");
echo $subFoo->getHelloName(), "\n"; // MUST OUTPUT: Hello, Joe.

return new static();

已有保留关键字static

您必须使用 Late Static Binding 创建对象 - 方法 get_called_class() 很有用。第二个选项是使用 static 关键字。

示例:

class Foo 
{
    private $name;

    public static function create($name) 
    {
        $object = get_called_class();
        return new $object($name);
    }

    private function __construct($name) 
    {
        $this->name = $name;
    }

    public function getName() 
    {
        return $this->name;
    }
}

class SubFoo extends Foo 
{
    public function getHelloName() 
    {
        return "Hello, ". $this->getName();
    }
}

$foo = Foo::create("Joe");
echo $foo->getName(), "\n";

$subFoo = SubFoo::create("Joe");
echo $subFoo->getHelloName(), "\n";

并输出:

Joe
Hello, Joe

是的,可以使用 php 的后期静态绑定功能。

而不是

$foo = Foo::create("Joe");
echo $foo->getName(), "\n"; // MUST OUTPUT: Joe

$subFoo = SubFoo::create("Joe");
echo $foo->getHelloName(), "\n"; // MUST OUTPUT: Hello, Joe.

试试这个

echo parent::getName();
echo self::getHelloName();