Getting static property from a class with dynamic

2019-01-07 09:40发布

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)

11条回答
Explosion°爆炸
2楼-- · 2019-01-07 10:14

You should be able to do something like:

eval("echo $classname::$propertyname;");

I just did a quick test and got this to work for me. Not sure if there's a better way or not, but I wasn't able to find one.

查看更多
Juvenile、少年°
3楼-- · 2019-01-07 10:15

Even if for you said eval is out of the question, prior PHP 5.3 the easiest solution is still by using eval:

eval("\$propertyval = $classname::\$propertyname;");
echo $propertyval;
查看更多
Explosion°爆炸
4楼-- · 2019-01-07 10:18

You can use ReflectionClass:

class foo
{
    private static $bar = "something";
}

$class = "foo";
$reflector = new ReflectionClass($class);
$static_vars = $reflector->getStaticProperties();
var_dump($static_vars["bar"]);
查看更多
Bombasti
5楼-- · 2019-01-07 10:18

To return a variable value that is set by a Static Variable you need to call:

$static_value = constant($classname.'::'.$propertyname);

Check out the documentation :: PHP Constant Documentation

查看更多
做自己的国王
6楼-- · 2019-01-07 10:18

'eval' looks so close to 'evil', and I hate using it and/or seeing it in code. With a few ideas from other answers, here's a way to avoid it even if your php isn't 5.3 or higher.

Changed to reflect testing based on a comment.

class A {
    static $foo = 'bar';
}

A::$foo = 'baz';
$a = new A;

$class = get_class($a);
$vars = get_class_vars($class);

echo $vars['foo'];

Outputs 'baz'.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-07 10:28

get_class_vars is not same as get_object_vars.

I think get_clas_vars should return the original property values.

查看更多
登录 后发表回答