Getting static property from a class with dynamic class name in PHP

treznik picture treznik · Aug 14, 2009 · Viewed 36.9k times · Source

I have this:

  • one string variable which holds the class name ($classname)
  • one string variable with holds the property name ($propertyname)

I want to get that property from that class, the problem is, the property is static and I don't know how to do that.

If the property weren't static, it would have been:

$classname->$propertyname;

if the property were a method, I could have used call_user_function

call_user_func(array($classname, $propertyname));

But in my case, am I just lost. I am however hoping that it is possible. With the thousands of functions that PHP has, he'd better have something for this as well. Maybe I'm missing something?

Thanks!

Edit:

  • for those with eval() solutions: thanks, but it is out of the question
  • for those with get _class _vars() solutions: thanks, but it seems it returns "the default properties of the given class" (php.net), and yes, I would like that value to be changable (even though it does help me in some of the cases)

Answer

Andrew Moore picture Andrew Moore · Aug 14, 2009

If you are using PHP 5.3.0 or greater, you can use the following:

$classname::$$propertyname;

Unfortunately, if you are using a version lower than 5.3.0, you are stuck using eval() (get_class_vars() will not work if the value is dynamic).

$value = eval($classname.'::$'.$propertyname.';');