How can you use a method from a parent controller to set a private variable in php?

45 views Asked by At

I have a simple MVC framework I'm using where I use the following call to load a model in each function in the controller:

$member_model = $this->loadModel('Members');

What I would like to do is call that once so every function in the Member Controller can use it rather than calling it in every function.

Something like:

class Members extends Controller
{
    private $member_model = $this->loadModel('Members');

    function myFunction(){
        myvar = $member_model->someFunction();
    }
}

Note: loadModel is a method of the Controller class of which the Members controller extends.

I get a range of different errors depending on whether the variable is private/public or neither however it works within a function.

Is it even possible to do this at the class level, if so how?

Update 1

Members Controller

class Members extends Controller
{

private $member_model = null;


function __construct()
{
    parent::__construct();
    $this->member_model = $this->loadModel('Members');

}
}

Controller Class

class Controller
{
function __construct()
{
    Session::init();

    try {
        $this->db = new Database();
    } catch (PDOException $e) {
        die('Database connection could not be established.');
    }

    $this->view = new View();
}

public function loadModel($name)
{
    $path = MODELS_PATH . strtolower($name) . '_model.php';

    if (file_exists($path)) {
        require MODELS_PATH . strtolower($name) . '_model.php';
        $modelName = $name . 'Model';
        return new $modelName($this->db);
    }
}
}
1

There are 1 answers

6
donald123 On

you can use it in a constructor

class Members extends Controller
{
  private $member_model = null;

  public function __constructor() {
       parent::_constructor(); 
       $this->member_model = $this->loadModel('Members');
    }
   function myFunction(){
    $myvar = $member_model->someFunction();
   }
}