【问题标题】:Mysqli in php class [duplicate]php类中的Mysqli [重复]
【发布时间】:2013-10-12 13:04:42
【问题描述】:

您好,我正在尝试使用 mysqli 而不是 mysql 来重建我的代码,但是我在 php 类中遇到了 mysql 的问题:

$db = new mysqli('localhost','user','password','dbname');

require_once('classes/some_class.php');
$some_class = new some_class();

在 some_class.php 中:

 class some_class {
  function __construct() { $db->query('blablabla'); }
 }

这不起作用,但是: 如果我在 some_class.php 中添加$db = new ...,它会起作用!

所以 some_class.php 不知道数据库连接:/

【问题讨论】:

  • $db->query(...) 是否包含在函数或类方法中?
  • 不是 some_class 而是你不知道的variable scope

标签: php mysql oop mysqli


【解决方案1】:

您的变量超出范围,some_class 不知道$db 是什么。您需要将$db 作为参数传递。您可以在实例化类时执行此操作。

$db = new mysqli('localhost','user','password','dbname');

require_once('classes/some_class.php');
$some_class = new some_class($db);
 //Pass $db here -------------^ to the constructor

这样就可以了。

class some_class {
    function __construct($db) { $db->query('blablabla'); }
}
//You receive $db here ---^

【讨论】:

  • 投反对票的是什么?
【解决方案2】:

some_class() 取决于您的 $db。

您有多种选择;

将依赖项作为参数传入:

$db = new mysqli('localhost','user','password','dbname');
// that could be in a different file

class some_class {
private $db;
function __construct($db) 
{
$this->db=$db; 
}
// eg - do a query
function getStuff($qry){
$this->db->query($qry); 
}
}

或

如你所说,让某个类实例化数据库连接

或

使用全局变量。

各有利弊。还有其他方法。如果你想真正理解每一个的含义,我建议你至少给自己找一本非常好的 OOP 书。这些东西很聪明,但要为每种情况找到正确的答案并不便宜。

【讨论】:

  • 我建议投票结束一个重复的问题,而不是试图抢夺一些代表点。
  • 一个多么卑鄙的人要投票给我。
猜你喜欢
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 2015-06-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 1970-01-01
  • 2017-02-28
相关资源
最近更新 更多