Can I get a static variable from the class string name?

Given the class string name in PHP, how can I access one of my static variables?

What I would like to do is:

$className = 'SomeClass'; // assume string was actually handed in as a parameter $foo = $className::$someStaticVar; 

... but PHP gives me the excellent "Syntax error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM", which is apparently the Hebrew name for the double colon (: :).

Update: Unfortunately, I have to use PHP 5.2.X for this.

Update 2: As suggested by MrXexxed, a static variable is inherited from the parent class.

+9
php static
Jul 28 '10 at 15:41
source share
4 answers

Reflection will do it

An employee just showed me how to do this with a reflection that works with PHP 5 (we are at 5.2), so I thought I would explain.

 $className = 'SomeClass'; $SomeStaticProperty = new ReflectionProperty($className, 'propertyName'); echo $SomeStaticProperty->getValue(); 

See http://www.php.net/manual/en/class.reflectionproperty.php

A similar trick works for methods.

 $Fetch_by_id = new ReflectionMethod($someDbmodel,'fetch_by_id'); $DBObject = $Fetch_by_id->invoke(NULL,$id); // Now you can work with the returned object echo $DBObject->Property1; $DBObject->Property2 = 'foo'; $DBObject->save(); 

See http://php.net/manual/en/class.reflectionmethod.php and http://www.php.net/manual/en/reflectionmethod.invoke.php

+15
Jul 29 '10 at 15:16
source share

What version of PHP are you running in? I believe above 5.3.x, this is allowed, but before that it is not.

EDIT: here you are using PHP 5.3.0, this is allowed Example # 2

 echo $classname::doubleColon(); // As of PHP 5.3.0 

Edit: For variables use

 echo $classname::$variable; // PHP 5.3.0 + 

here is the link

Edit 3: Try this link , the answer from there seems to be applicable to your situation.

+7
Jul 28 '10 at 15:45
source share

This is only possible in PHP 5.3 and later versions of late static bindings .

The workaround for older versions of PHP that come to me first is & mdash; please do not offend me. using eval() :

 if (class_exists($className)) { eval('$foo = ' . $className . '::$someStaticVar;'); } 

By the way, when accessing static variables, $ before the variable name is required, as in $someStaticVar .

+1
Jul 28 '10 at 15:46
source share

You may need to use reflection classes. http://www.php.net/manual/en/reflectionfunctionabstract.getstaticvariables.php

Or use the simple eval: print "{$className::$someStaticVar}" , which replaces $ className before looking for :: $ someStaticVar. Not sure about PHP <5.2 though.

+1
Jul 28 '10 at 15:49
source share



All Articles