PHP – Why No Facility to Overload Static Properties?

method-overloadingPHPstatic-accessstatic-keyword

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 declared static.

But why?

My questions are:

  1. Is there a technical reason that this functionality is not currently supported? Or perhaps a (shudder) political reason?
  2. 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.

Best Answer

Quoting http://marc.info/?l=php-internals&m=121578194822276&w=2

Was static member overloading added in PHP 5.3? I noticed that static method overloading was (__callStatic). The two would complement each other and it just seems natural to add these as well. I did notice that they are apart of the "static-class" RFC and a bug report, but it would be nice to see these in 5.3. With this addition and LSB, php classes can do so much! Ex:

__setStatic()
__getStatic()
__issetStatic()
__unsetStatic()

Quoting follow-up http://marc.info/?l=php-internals&m=121578318524848&w=2

if the RFC for static classes will be accepted, static property interceptors will be a part of the next PHP major version (might it be 5.4 or 6). So it won't make it into 5.3, but we will have that hopefully in the future.

Link to Static Classes RFC:

The Status of the RFC is "in the works" but given that it is from 2008 you might want to ask on the php.internals mailing list or on #php.pecl on EFNet IRC to find out what has become of it.