There is a shortcut method to create an object from a method that return a string?
For the moment, I used that :
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();
There is short-cut syntax for getting the string but not for creating the object from the string to date in PHP. See the following code in which I also include a 'myEntityName' class:
<?php
class myEntityName {
public function __construct(){
echo "Greetings from " . __CLASS__,"
";
}
}
class MyClass {
/**
* @return string
*/
public function getEntityName() {
return 'myEntityName';
}
}
$entityName = ( new MyClass() )->getEntityName();
$entity = new $entityName();
With one line the code instantiates a MyClass object and executes its getEntityName method which returns the string $entityName. Interestingly, if I replace my one-liner with the following it fails in all versions of PHP except for the HipHop Virtual Machine (hhvm-3.0.1 - 3.4.0):
$entityName = new ( ( new MyClass() )->getEntityName() );