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)
I think this is the simplest:
Getting and setting both static and non static properties without using Reflection
Using Reflection works but it is costly
Here is what I use for this purpose,
It works for
PHP 5 >= 5.1.0
because I'm usingproperty_exist
If you are using PHP 5.3.0 or greater, you can use the following:
Unfortunately, if you are using a version lower than 5.3.0, you are stuck usingeval()
(get_class_vars()
will not work if the value is dynamic).EDIT: I've just said
get_class_vars()
wouldn't work if the value is dynamic, but apparently, variable static members are part of "the default properties of a class". You could use the following wrapper:Unfortunately, if you want to set the value of the variable, you will still need to use
eval()
, but with some validation in place, it's not so evil.set_user_prop()
with this validation should be secure. If people start putting random things as$className
and$property
, it will exit out of the function as it won't be an existing class or property. As of$value
, it is never actually parsed as code so whatever they put in there won't affect the script.Potentially relevant: discussion on late static binding in PHP - When would you need to use late static binding?.
One thing I noticed is that you can't set variables which are protected in static classes as the eval() command runs in a scope outside the class. The only thing to get around this would be to implement a static method inside the/every class which runs the eval(). This method could be protected as the call_user_func() [to call the setter method] also runs from inside the class.