Instantiating a class can use it in all functions of the same class

Asked

Viewed 156 times

3

I wonder if I can instantiate another class just once and use it in all other functions of my current class.

Sample code:

require ('model.php');
class search{
    function __construct(){
        $objModel = new Model();}
    function insert(){
        $nome = "Alguém";
        $objModel->inserir($nome);}

    function select(){
        $idade = 30;
        $objModel->buscar($idade);}
}

When I try to do this it returns an error stating that the $objModel variables that are within the methods have not been initialized. I’d like to settle this without having to put one $objModel = new Model() in each function, if possible.

1 answer

4


Try declaring the variable $objModel as a class attribute and call using the $this->objModel:

class search{
    private $objModel;
    function __construct(){
        $this->objModel = new Model();
    }
    function insert(){
        $nome = "Alguém";
        $this->objModel->inserir($nome);
    }
    function select(){
        $idade = 30;
        $this->objModel->buscar($idade);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.