好吧,我已經做出了單獨的類連接到我的數據庫和類是在一個單獨的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