从另一个类获取已创建的mysqliDb连接

时间:2016-07-29 08:31:13

标签: php mysql class mysqli

我有MysqliDb https://github.com/joshcam/PHP-MySQLi-Database-Class

在我的php课程中:

<?php 
require_once ('MysqliDb.php');

class Main{

protected $db;   


public function __construct()
{
    $this->db = new MysqliDb ('localhost', 'root', 'tuncay', 'db');
}

}

Class A extends Main{

public function __construct()
{   
    $this->db = MysqliDb::getInstance();
    echo $this->db->where("id", 5)->getOne('test')['text'];
}

}

$a = new A();

?>

Php错误:致命错误:在第21行的/.../db/index.php中调用成员函数where()on null where()函数属于MysqliDb.php

有什么问题?我从Main class获得了$ this-&gt; db

我只想在A类中保留数据库连接并使用它。

2 个答案:

答案 0 :(得分:2)

您的A类替换父级__construct。尝试添加

Class A extends Main{
  public function __construct()
  {   
     parent::__construct();
     $this->db = MysqliDb::getInstance();
     echo $this->db->where("id", 5)->getOne('test')['text'];
  }
  ...
}

答案 1 :(得分:1)

那么你的意思是我可以这样做:

<?php 
require_once ('MysqliDb.php');

class Main{

  protected  $db;   

   public function connectDB()
   {
    $this->db = new MysqliDb ('localhost', 'root', 'pass', 'db');
   }
}

Class A extends Main{
   public function __construct()
   {   
    $this->connectDB();
    echo $this->db->where("id", 5)->getOne('test')['text'];
   }
}

$a = new A();
?>

这是正常的吗?我的意思是,每次调用connectDB()函数都不会损坏内存?或者每次都会调用相同的记忆部分......?

相关问题