0

I have this class:

class template {

    private $_db;

    public function __construct(){

        $this->_db = \MysqliDb::getInstance();
    }


    public function get(){

        return $this->_db->rawQuery("SHOW COLUMNS FROM rank LIKE 'view_template'");
    }
}

But, when I execute the method get, I get this error message:

Fatal error:  Call to a member function rawQuery() on a non-object in {dir/to/my/file} on line 50

Line 50 is return $this->_db->rawQuery("SHOW COLUMNS FROM rank LIKE 'view_template'");

The weird thing is that it works fine if I move the code from __construct to the get method, like this:

class template {

    private $_db;

    public function get(){

        $this->_db = \MysqliDb::getInstance();
        return $this->_db->rawQuery("SHOW COLUMNS FROM rank LIKE 'view_template'");
    }
}

What can be wrong in this case?

thingNumber2
  • 123
  • 1
  • 8
  • 1
    It sounds like the instance isn't actually available when you instantiate the `template` class, but it is later on when you call get. – alzee Apr 22 '17 at 16:23
  • 1
    Suppose you call the method statically, without instantiating the class, show how you call get() method – Mikhail Apr 22 '17 at 16:32
  • @alzee @Mikhail Thanks, you are right. I was initializating the class template, then the class Mysqlidb and then executing the `get` method so you were completly right about the moment when is available and the issue was related to the way I was calling the classes and methods. – thingNumber2 Apr 22 '17 at 16:40
  • 1
    In the constructor, if the result of getinstance is invalid, you should throw an exception. Not just here, but in any other classes like this that you write. It'll make it easier to track down problems like this. – alzee Apr 22 '17 at 17:40
  • Good advice. Thanks. – thingNumber2 Apr 22 '17 at 17:43

1 Answers1

1

I think

\MysqliDb::getInstance()

; isn't returning a valid object at the time when the construct is called, this is why you are getting the error.

You could check the object returned in the construct to see if a valid object is returned before calling the get method

public function __construct(){ $this->_db = \MysqliDb::getInstance(); var_dump( $this->_db); }

Tosin
  • 116
  • 1
  • 3