From the string name of a class, can I get a stati

2019-01-15 01:15发布

问题:

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.

回答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



回答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.



回答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.



回答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.



标签: php static