好吧,我已经做出了单独的类连接到我的数据库和类是在一个单独的PHP文件PHP未定义类变量
connect.php
class connect{
function __construct(){
// connect to database
}
function query($q){
// executing query
}
}
$connect = new connect();
现在,我做的对象类$连接,当在一个文件中使用像的index.php它的工作原理
的index.php
require_once('connect.php');
$set = $connect->query("SELECT * FROM set");
现在,在这里它工作正常,我没有重新创建的类的对象,并直接执行查询,其中在另一个文件名为header.php中我有这样
的header.php类
class header{
function __construct(){
require_once('connect.php');
// Here the problem arises i have to re declare the object of the connection class
// Without that it throws an error undefined variable connect
$res = $connect->query("SELECT * FROM table");
}
}
为什么它在index.php上工作,而不是在header.php上,我希望你明白我在说什么
除了不好的做法,它sh会工作。更好的方法是做'new header($ connect)',例如注入依赖关系。 – Gordon 2012-02-13 09:22:22
'require_once('connect.php');'在头文件类的'__construct()'中的类头文件和全局$连接;'之外.. – ahmet2106 2012-02-13 09:25:53
@ ahmet2106 [请忘记'全局'存在](http:// stackoverflow.com/questions/5166087/php-global-in-functions/5166527#5166527) – Gordon 2012-02-13 09:26:20