Im having a problem with using a variable as the class name when calling a static function within the class. My code is as follows:
class test {
static function getInstance() {
return new test();
开发者_如何学C }
}
$className = "test";
$test = $className::getInstance();
Ive got to define the class name to a variable as the name of the class is coming from a database so i never know what class to create an instance of.
note: currently i am getting the following error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
Thanks
$test = call_user_func(array($className, 'getInstance'));
See call_user_func and callbacks.
You could use the reflection API, that would let you do something like:
$className = 'Test';
$reflector = new ReflectionClass($className);
$method = $reflector->getMethod('getInstance');
$instance = $method->invoke(null);
or even:
$className = 'Test';
$reflector = new ReflectionClass($className);
$instance = $reflector->newInstance();
// or $instance = $reflector->newInstanceArgs([array]);
// or $instance = $reflector->newInstanceWithoutConstructor();
Both seem a lot cleaner to me than just interpreting the value of a string directly as a class name or using call_user_func
and friends.
精彩评论