2013-10-05 36 views
1

嗨,我试图重建我的代码库MySQLi而不是MySQL,但我有一个问题,在一个PHP类的mysql:在mysqli的PHP类

$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不知道数据库连接:/

+0

是包含在函数或类方法中的'$ db-> query(...)'吗? – ComFreek

+2

它不是some_class,而是你不知道[变量范围](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-在哪里和) –

回答

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 ---^ 
+0

什么是反对票? –

1

some_class()是取决于你的$分贝。

你有几个选择;

传递依赖于作为参数:

$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); 
} 
} 

OR

正如你所说的,已经SomeClass的实例数据库连接

OR

使用全局变量。

每个人都有优点和缺点。还有其他的方法。如果你想真正理解每一个的含义,我建议你至少找到一本非常好的面向对象的书。这些东西很聪明,但为每种情况找到正确的答案并不便宜。

+1

我会建议投票结束一个过度重复的问题,而不是试图抢夺一些重点。 –

+0

某人的意气风发让我失望。 – Cups