From the string name of a class, can I get a static variable?

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

What I’d like to do is this:

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

…but PHP gives me a lovely “Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM”, which apparently is a Hebrew name for the double colon(::).

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

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Reflection will do it

A coworker just showed me how to do this with reflection, which works with PHP 5 (we’re on 5.2), so I thought I’d 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

Solution 2

Which version of PHP are you running? I believe above 5.3.x this is allowed but before that it isn’t.

EDIT: here you go as of PHP 5.3.0 it’s allowed
Example #2

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

Edit:
For variables use

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

here’s the link

Edit 3:
Try this link the answer from there seems like it would apply to your situation.

Solution 3

That’s only possible in PHP 5.3 and later with late static bindings.

The workaround for older versions of PHP that first comes to my mind is — please don’t hurt me — using eval():

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

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

Solution 4

You might have to use the reflection classes. http://www.php.net/manual/en/reflectionfunctionabstract.getstaticvariables.php

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

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply