用于从方法创建新对象的漂亮语法


Nice Syntaxe for creating new object from method

有一个快捷方式方法可以从返回字符串的方法创建对象?

目前,我使用了:

class MyClass {
    /**
     * @return string
     */
    public function getEntityName() {
        return 'myEntityName';
    }
}
$myClassInstance = new MyClass();
// Need to get string
$entityName = $myclassInstance->getEntityName();
// And after I can instantiate it
$entity = new $entityName();
在 PHP 中,有用于获取字符串的

快捷方式语法,但不能用于从字符串创建对象。 请参阅以下代码,其中还包括一个"myEntityName"类:

<?php
class myEntityName {
    public function __construct(){
        echo "Greetings from " . __CLASS__,"'n";
    }
}
class MyClass {
    /**
     * @return string
     */
    public function getEntityName() {
        return 'myEntityName';
    }
}
$entityName = ( new MyClass() )->getEntityName();
$entity = new $entityName();

代码使用一行实例化 MyClass 对象执行其返回字符串$entityName的 getEntityName 方法。有趣的是,如果我用以下内容替换我的单行代码,则在除 HipHop 虚拟机 (hhvm-3.0.1 - 3.4.0) 之外的所有 PHP 版本中都会失败:

$entityName = new ( ( new MyClass() )->getEntityName() );