Access parent scope from nested class

633 views php

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:


From within:


I imagine I would need something like:


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


If MY_SOMETHING has a dependency on MY_ANOTHERTHING, inject it!

  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?


Please login first before posting an answer.