secondman
secondman

Reputation: 3277

Determining Proper Class Scope PHP

I have a model class ModelHome that is a child of Model ie:

class ModelHome extends Model

Model is a variable of the Controller class ie:

class Controller {

    public $model;

    public function __construct () {
        $this->model = new Model;
    }
}

Is it possible to access a method within the Controller class from within a method inside the ModelHome class?

I've tried parent:: and calling the class by name ie Controller::method but I can't seem to find the right scope to access the method I need.

Thanks.

-Vince

Upvotes: 1

Views: 53

Answers (1)

Alfred Godoy
Alfred Godoy

Reputation: 1043

First of all, you must have an instance of ModelHome. If you make an instance of Model, that has not automatically been extended by ModelHome just because ModelHome exists. So, i guess your Controller::__construct() should be:

public function __construct () {
    $this->model = new ModelHome;
}

However, your ModelHome does not know about your Controller class/instance. You could make a __construct in ModelHome that takes a parameter with a link to the controller. Like this:

class ModelHome extends Model {

    public $controller;

    public function __construct ($controller) {
        $this->controller = $controller;
    }
}

class Controller {

    public $model;

    public function __construct () {
        $this->model = new ModelHome($this);
    }
}

Now, your ModelHome knows about the controller by using $this->controller

Upvotes: 2

Related Questions