Why is there no facility to overload static properties in PHP?
Posted
by
Jon
on Programmers
See other posts from Programmers
or by Jon
Published on 2012-03-20T10:33:45Z
Indexed on
2012/03/20
17:38 UTC
Read the original article
Hit count: 284
Intro
PHP allows you to overload method calls and property accesses by declaring magic methods in classes. This enables code such as:
class Foo {
public function __get($name) { return 42; }
}
$foo = new Foo;
echo $foo->missingProperty; // prints "42"
Apart from overloading instance properties and methods, since PHP 5.3.0 we can also overload static
methods calls by overriding the magic method __callStatic
.
Something missing
What is conspicuously missing from the available functionality is the ability to overload static properties, for example:
echo Foo::$missingProperty; // fatal error: access to undeclared static property
This limitation is clearly documented:
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 declaredstatic
.
But why?
My questions are:
- Is there a technical reason that this functionality is not currently supported? Or perhaps a (shudder) political reason?
- Have there been any aborted attempts to add this functionality in the past?
Most importantly, the question is not "how can I have dynamic static properties in userland PHP?". That said, if you know of an especially cute implementation based on __callStatic
that you want to share then by all means do so.
© Programmers or respective owner