PHP5 Static Property Inheritance / Overloading Issue Resolved

May 17th, 2007

Here is the issue:

I need to use a static variable that changes with the sub class (db table, for example). It must be static because I need to use it in some static methods which don't know about $this (object context). The problem is that in php5, the 'self' keyword is always called in the context where it is written, so if you've got a method that's inherited, that's calling self::$something in the parent, you're going to get the parent value of $something. boo.

Static variables are also not available through $this->foo notation.



       abstract class a {
               public static $lala = '1';
               function __construct () {
                       echo self::$lala;
               }
       }

       class b extends a {
               public static $lala = '2';
       }

       new b();

This outputs '1'. Argh.

There's a bug filed for this behavior, but the php developers have sort of passed on it.

The workaround, I discover, is this:


 /* crazy workaround for the fact that 'self' does not follow inherited context */
private function table() {
       $vars = get_class_vars(get_class($this));
       return $vars['table'];
}

This replaces the static var with a non-static method so that it inherits nicely, and works around the brokenness of 'self'. Hmm. "Brokenness of self" sounds like a good title for some minimalist emo industrial track.

I hope this makes sense. It almost does to me. More to the point my code is now working, which makes me happy.

It's late, though, and it could be delirium.

Leave a Reply