【问题标题】:Access parent scope from nested class从嵌套类访问父范围
【发布时间】:2019-04-10 11:47:41
【问题描述】:

我有一个主要课程,例如

class MY_API {
    function __construct($db) {
        $this->something = new MY_SOMETHING($db);
        $this->anotherthing = new MY_ANOTHERTHING($db);
    }
}

所以我可以使用 $this->something->somefunction();

但我不确定如何访问:

$this->anotherthing->anotherfunction();

从内部:

$this->something->somefunction();

我想我需要类似的东西:

$this->parent->anotherthing->anotherfunction();

这可能吗,还是我需要改变构建课程的方式?

理想情况下,我只是希望这些函数位于不同的文件中,而不是拥有一个非常大的文件,并且每个文件中的每个函数都可以相互访问

【问题讨论】:

    标签: php class inheritance


    【解决方案1】:

    如果MY_SOMETHING 依赖于MY_ANOTHERTHING,注入它!

    class MY_SOMETHING {
      private $db;
      private $anotherThing;
    
      public function __construct($db, MY_ANOTHERTHING $anotherThing) {
        $this->db = $db;
        $this->anotherThing = $anotherThing;
      }
    

    在你的 MY_API 构造函数中

    public function __construct($db) {
        $this->anotherthing = new MY_ANOTHERTHING($db);
        $this->something = new MY_SOMETHING($db, $this->anotherThing);
    }
    

    现在您的MY_SOMETHING 类可以在其任何方法中使用$this->anotherThing

    【讨论】:

    • 好吧,这是有道理的,如果他们每个人都需要互相访问函数呢?理想情况下,我希望所有类都可以访问所有其他类,这样我就可以轻松组织我的代码
    • 这听起来不像是组织,更像是一团糟。也许您不想使用 OOP,而只想要一堆函数(全局或命名空间)
    • 感谢 Phil,当所有函数都位于主类中时它可以工作,但是我只是试图在不同文件之间分解代码,因此将一些函数拆分为它们自己的类,但这会停止我无法引用每个子类函数,扩展类似乎不是一个好的解决方案,也许我只需要处理一个很长的类文件
    • 我建议您阅读有关 OOP 的 SOLID principals,特别关注 S ~ “单一职责原则 - 一个类应该只有单一职责”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2011-07-03
    • 2013-05-22
    • 2013-08-06
    • 1970-01-01
    • 2022-08-16
    • 2020-11-15
    相关资源
    最近更新 更多