dongtuwu8548 2018-11-07 02:27
浏览 72
已采纳

从嵌套类访问父作用域

I have a main class e.g.

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

SO I can access this with $this->something->somefunction();

But I am not sure how I could access:

$this->anotherthing->anotherfunction();

From within:

$this->something->somefunction();

I imagine I would need something like:

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

Is this possible at all, or do I need to change the way I am building the classes?

Ideally I just want these functions to sit in a different file rather than having one very large file and have each function in each file accessible to each other

  • 写回答

1条回答 默认 最新

  • dongzichan2886 2018-11-07 02:32
    关注

    If MY_SOMETHING has a dependency on MY_ANOTHERTHING, inject it!

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

    and in your MY_API constructor

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

    Now your MY_SOMETHING class can use $this->anotherThing in any of its methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题