Access parent scope from nested class

633 views php
2

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

answered question

1 Answer

3

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.

posted this

Have an answer?

JD

Please login first before posting an answer.