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

会有一股神秘感。 提交于 2019-12-04 03:33:38

问题


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.



来源:https://stackoverflow.com/questions/1203810/is-there-a-way-to-have-php-subclasses-inherit-properties-both-static-and-instan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!