Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a static variable by $var::$reference

Tags:

php

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 use call_user_func():

class foo {     function bar() { echo 'hi'; } }  $class = 'foo'; call_user_func(array($class, 'bar')); // prints hi 

However, this does not work when trying to access a static variable within the class:

class foo {     public static $bar = 'hi'; }  $class = "foo"; call_user_func(array($class, 'bar')); // nothing echo $foo::$bar; // invalid 

How do I get at this variable? Is it even possible? I have a bad feeling this is only available in PHP 5.3 going forward and I'm running PHP 5.2.6.

like image 386
chuckg Avatar asked Mar 23 '09 23:03

chuckg


People also ask

How do you access a static variable?

Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.

Can we access static variables using object reference?

Static variables can also be accessed by the object reference but an instance variable can only be accessed by the object reference.

How do you call a static variable outside the package?

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.

How do I use a static variable in VBA?

In form modules, static variables retain their value until the form is closed. Use the Static statement in nonstatic procedures to explicitly declare variables that are visible only within the procedure, but whose lifetime is the same as the module in which the procedure is defined.


1 Answers

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

like image 177
Karol Avatar answered Sep 21 '22 13:09

Karol