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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题