Instantiating a class and using it in all functions of the same class

3

I would like to know 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 would like to resolve this without having to put a $objModel = new Model() on each function, if at all possible.

    
asked by anonymous 01.01.2016 / 03:26

1 answer

4

Try to declare the variable $objModel as an attribute of the class and make a call using $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);
    }
}
    
01.01.2016 / 03:33