【问题标题】:get already created mysqliDb connection from another class从另一个类获取已经创建的 mysqliDb 连接
【发布时间】:2016-12-03 21:26:50
【问题描述】:

我有 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();

?>

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

怎么了?我从主类得到 $this->db

我只是想在A类中保持DB连接并使用它。

【问题讨论】:

  • hmm...如果您之前没有设置过 Main 类,那么就没有要保留的 DB 连接!?也许你想做parent::_construct()

标签: php mysql class php-mysqlidb


【解决方案1】:

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

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

【讨论】:

  • 这行$this-&gt;db = MysqliDb::getInstance(); 没有意义,或者不需要。
  • 在 A 类中,我只想使用 Main 类中的 $this->db。如果我使用 parent::_construct 则连接将再次重复。正常吗?
  • 现在你的子构造只是替换你的父构造并且$this-&gt;db = new MysqliDb ('localhost', 'root', 'tuncay', 'db');不要使用。如果您添加parent::__construct(),它将被使用。
  • 内存呢??每次调用同一个函数 parent::_constract 或 connectDB ...还是每次内存都一样?
【解决方案2】:

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

<?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()函数都不会损坏内存吗?还是每次都会调用内存的同一部分...?

【讨论】:

    猜你喜欢
    • 2015-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    相关资源
    最近更新 更多