Getting static property from a class with dynamic class name in PHP

后端 未结 11 482
情歌与酒
情歌与酒 2020-11-30 01:44

I have this:

  • one string variable which holds the class name ($classname)
  • one string variable with holds the property name ($propert
相关标签:
11条回答
  • 2020-11-30 02:08

    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

    0 讨论(0)
  • 2020-11-30 02:10

    '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'.

    0 讨论(0)
  • 2020-11-30 02:10

    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.

    0 讨论(0)
  • 2020-11-30 02:14

    get_class_vars is not same as get_object_vars.

    I think get_clas_vars should return the original property values.

    0 讨论(0)
  • 2020-11-30 02:15

    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.

    0 讨论(0)
提交回复
热议问题