Access a static variable by $var::$reference

前端 未结 4 626
温柔的废话
温柔的废话 2020-12-10 00:30

I am trying to access a static variable within a class by using a variable class name. I\'m aware that in order to access a function within the class, you

相关标签:
4条回答
  • 2020-12-10 01:04

    I think there is much better (more elegant) way then creating ReflectionClass instance. I also edited this code (and my answer) after few comments. I added example for protected variables (you can't of course access them from outside the class, so I made static getter and call it using variable pattern as well). You can use it in few different ways:

    class Demo
    {
        public static $foo = 42;
        protected static $boo = 43;
        public static function getProtected($name) {
            return self::$$name;
        }
    }
    
    $var1 = 'foo';
    $var2 = 'boo';
    $class = 'Demo';
    $func = 'getProtected';
    var_dump(Demo::$$var1);
    var_dump($class::$foo);
    var_dump($class::$$var1);
    //var_dump(Demo::$$var2); // Fatal error: Cannot access protected property Demo::$boo
    var_dump(Demo::getProtected($var2));
    var_dump($class::getProtected($var2));
    var_dump($class::$func($var2));
    

    Documentation is here:

    http://php.net/manual/en/language.variables.variable.php

    0 讨论(0)
  • 2020-12-10 01:06

    For calling static members you can use a code like this:

    call_user_func("MyClass::my_static_method");
    // or
    call_user_func(array("MyClass", "my_static_method"));
    

    Unfortunately the only way to get static members from an object seems to be get_class_vars():

    $vars = get_class_vars("MyClass");
    $vars['my_static_attribute'];
    
    0 讨论(0)
  • 2020-12-10 01:23

    You can use reflection to do this. Create a ReflectionClass object given the classname, and then use the getStaticPropertyValue method to get the static variable value.

    class Demo
    {
        public static $foo = 42;
    }
    
    $class = new ReflectionClass('Demo');
    $value=$class->getStaticPropertyValue('foo');
    var_dump($value);
    
    0 讨论(0)
  • 2020-12-10 01:23

    Have you try this?

    class foo {
        static public $bar = "Hi";
    
        static public function bar() {
            echo "Hi";
        }
    }
    
    echo foo::$bar; // Output: Hi
    foo::bar(); // Output: Hi
    
    $class = "foo";
    echo $class::$bar; // Output: Hi
    $class::bar(); // Output: Hi
    call_user_func($class, 'bar'); // Output: Hi
    
    0 讨论(0)
提交回复
热议问题