有没有办法让PHP子类继承属性(静态和实例)? [英] Is there a way to have PHP subclasses inherit properties (both static and instance)?

查看:97
本文介绍了有没有办法让PHP子类继承属性(静态和实例)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我按如下方式声明基类:

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);
     }

}

然后扩展它:

class Child extends Parent {
}

然后执行此操作:

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?

我只是想知道是否有关于PHP的后期静态绑定以及允许继承的内容为了这。我已经习惯了这个问题...但是,一个未声明的静态属性会回落到它的父级值上似乎没有意义!?

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

推荐答案

答案是有一个解决方法。

The answer is "with a workaround".

你必须创建一个静态构造函数并调用它来复制该物业。

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

这篇关于有没有办法让PHP子类继承属性(静态和实例)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆