douliu1092 2017-11-14 11:03
浏览 22
已采纳

一旦创建了扩展的对象,就调用类方法

Assume we have the following class (simplified):

class SuperConfig {
    public $mainDir;

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

This class is supposed to be extended in EVERY other class in the project, and I do need the setDir() function of the parent to be executed. Obviously, I could do it like this:

class A extends SuperConfig() {
    public function __construct() {
        parent::setDir();
    }
    // ... other stuff is about to be done ...
}

and I could access the properties in the child class like this:

class A extends SuperConfig {
    public function doSomething() {
        SuperConfig::mainDir;
    }
}

This is a viable solution, but I got multiple hundreds of classes and doing this in every single one seems tedious. So, is there a way to do something like this:

class SuperConfig {
    public $mainDir;

    public function __extend() {
        $this->setDir();
    }

    public function setDir() {
        $this->mainDir = "path/to/dir";
    }
}

__extend() obviously doesn't work like that, but I'm wondering is there is a trick how I could make this work.

  • 写回答

4条回答 默认 最新

  • doushui3061 2017-11-14 11:07
    关注
    class SuperConfig {
        public $mainDir;
    
        public function __construct() {
            $this->setDir();  // consider moving setDir's code here as well,
                              // unless you have a good reason for it to be a method
        }
    
        public function setDir() {
            $this->mainDir = "path/to/dir";
        }
    }
    

    You simply do this, and then you expect all subclasses to call the parent constructor if they're overriding the constructor:

    public function __construct() {
        parent::__construct();
        // more code
    }
    

    It's perfectly reasonable to expect children to call their parent constructor, unless they deliberately want to leave the instance in an unknown and potentially broken state.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题