phpinheritancelate-static-binding

Is there a way to have PHP subclasses inherit properties (both static and instance)?


If I declare a base class as follows:

abstract class Parent {

  protected static $message = "UNTOUCHED";

     public static function yeah() {
         static::$message = "YEAH";
     }
     public static function nope() {
         static::$message = "NOPE";
     }

     public static function lateStaticDebug() {
         return(static::$message);
     }

}

and then extend it:

class Child extends Parent {
}

and then do this:

Parent::yeah();
Parent::lateStaticDebug();  // "YEAH"

Child::nope();
Child::lateStaticDebug();  // "NOPE"

Parent::yeah();
Child::lateStaticDebug()   // "YEAH"

Is there a way to have my second class that inherits from the first also inherit properties and not just methods?

I'm just wondering if there's something about PHP's late static binding and also inheritance that would allow for this. I'm already hacking my way around this...But it just doesn't seem to make sense that an undeclared static property would fall back on its parent for a value!?


Solution

  • The answer is "with a workaround".

    You have to create a static constructor and have it called to copy the property.