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.
Since static variables belong to a class, we can access them directly using the class name. So, we don't need any object reference.
A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.
From outside the class, "static variables should be accessed by calling with class name." From the inside, the class qualification is inferred by the compiler.
Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With