Is it possible to test if a variable is static in PHP? I am trying create a magic method __get
that also looks at static variables. I find that property_exists()
returns true when a variable is static too. But I will need to use ::
instead of ->
I'd expect?

- 193,403
- 52
- 435
- 836

- 2,417
- 7
- 33
- 46
-
You mean class property/variable rather than local variable? – BoltClock Jul 04 '11 at 08:10
-
@BoltClock yes. a variable declared like `protected static $var` – JM at Work Jul 04 '11 at 08:27
-
1possible duplicate of [Magic __get getter for static properties in PHP](http://stackoverflow.com/questions/1279382/magic-get-getter-for-static-properties-in-php) – Gordon Jul 04 '11 at 08:52
2 Answers
It is possible to test if a variable is static via Reflection:
class Foo { static $bar; }
$prop = new ReflectionProperty('Foo', 'bar');
var_dump($prop->isStatic()); // TRUE
However, that still won't allow you to use them with magic methods __get
or __set
, because those only work in object context. From the PHP Manual on Magic Methods:
Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0, a warning is issued if one of the magic overloading methods is declared static.
Also see this discussion on the PHP Internals Mailing List about introducing __getStatic
:

- 312,688
- 75
- 539
- 559
-
I managed to do it with something like `return static::$$prop` :) or is there something wrong with that? – JM at Work Jul 04 '11 at 09:08
-
@JM having to use late static binding and variable variables are not exactly indicators of good design. [Statics are death to testability](http://sebastian-bergmann.de/archives/883-Stubbing-and-Mocking-Static-Methods.html) and [considered harmful](http://kore-nordmann.de/blog/0103_static_considered_harmful.html) – Gordon Jul 04 '11 at 09:14
I don't think you can access undeclared static property using magic __get() method. It will raise PHP Fatal error. At least with PHP of version 5.3.
That's the result if you will try to access the property as static ClassName::$propertyName
of course.

- 3,592
- 1
- 21
- 29
-
-
1@JM It is declared private, so it's like it's undeclared if you use it outside of the class – Matthieu Napoli Jul 04 '11 at 09:02