Is there a way to have PHP subclasses inherit prop

2019-02-24 00:09发布

问题:

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!?

回答1:

Inheritance and static properties does sometime lead to "strange" things in PHP.

You should have a look at Late Static Bindings in the PHP's manual : it explains what can happen when inheriting and using static properties in PHP <= 5.2 ; and gives a solutions for PHP >= 5.3 where you can use the static:: keywords instead of self::, so that static binding is done at execution (and not compile) time.



回答2:

The answer is "with a workaround".

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