简体   繁体   中英

Fatal error: Call to a member function query() on a non-object

This is my base database class:

class _getDatabase
{
    private $db;

    function __construct(PDO $connection)
    {
        $this->db = $connection;
    }

    /* Selection wrapper*/

    public function getSelected($requestDatabase, $arguments)
    {

        foreach ($requestDatabase as $getBranchDatabase) {
        $this->db->query('USE '. $getBranchDatabase); //error on this line
        $sql = $this->db->prepare($arguments['query']);
        $sql->execute(array(
            $arguments['parameters']
        ));
        return $sql->fetchALL(PDO::FETCH_OBJ);
      }
    }

}

$dbh = new PDO('XXXXX');
$dbFactory = new _getDatabase($dbh);

This is my child class:

function __autoload($classname)
{
    $filename = "../database/" . $classname . ".php";
    include_once($filename);
}
class _getBranch extends _getDatabase
{
    public $requestDatabase = array();

    public function __construct(array $selectedBranch)
    {

        $this->branch = $selectedBranch;

    }

    public function getBranch($query)
    {
        parent::getSelected($this->branch, $query);
    }
}
$setDbObject = new _getBranch(array(
    "esoftcar_jaf",
    "esoftcar_jaf"
));
$arguments = array();
$arguments['query']      = 'SELECT * FROM `branches` WHERE B_CODE = ?';
$arguments['parameters'] = 'AMB';
var_dump($setDbObject->getBranch($arguments)); 

Now I'm getting the following error:

PHP Fatal error: Call to a member function query() on a non-object

What am I doing wrong?

Your DB connection is failing, because $this->db doesn't exist.

You are calling the getSelected() method from the parent which is good, but the $this->db value is never declared and initiated because the parent constructor isn't called..

In __construct() use

parent::__construct($connection);

To fix this.

The error is telling you that the $db attribute of the __getDatabase class is not initialized, and that is because you are not passing the db connection to the parent class constructor from the child class.

When you create the child class, it is not magically using the parent class you created in the $dbFactory line.

One possible solution would be to put initialize the connection within the child class constructor and pass it over to the parent class constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM