PHP: variable name as an instance of a class

I'm having a problem using a variable as a class name when calling a static function inside a class. My code is as follows:

class test {
     static function getInstance() {
         return new test();
     }
}

$className = "test";
$test = $className::getInstance();

I need to determine the class name for the variable, since the class name comes from the database, so I never know which class to instantiate.

note: I am currently getting the following error:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM 

thank

+3
source share
2 answers
$test = call_user_func(array($className, 'getInstance'));

See call_user_func and callbacks .

+8
source

API , - :

$className = 'Test';
$reflector = new ReflectionClass($className);
$method = $reflector->getMethod('getInstance');
$instance = $method->invoke(null);

:

$className = 'Test';
$reflector = new ReflectionClass($className);
$instance = $reflector->newInstance(); 
// or $instance = $reflector->newInstanceArgs([array]);
// or $instance = $reflector->newInstanceWithoutConstructor();

, call_user_func .

0

Source: https://habr.com/ru/post/1728844/


All Articles