3

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();
     }
}

$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

2
  • Funnily enough, your code works for me in PHP 5.3.1 and does not throw an error. Commented Jan 17, 2010 at 20:51
  • 1
    variable static classes are available in PHP 5.3+, anything lower requires call_user_func() / call_user_func_array() as mentioned by @hobodave Commented Jan 17, 2010 at 20:53

2 Answers 2

8
$test = call_user_func(array($className, 'getInstance'));

See call_user_func and callbacks.

Sign up to request clarification or add additional context in comments.

1 Comment

Only way until 5.3 that is, in 5.3+ you can use variable classnames.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.