【发布时间】:2012-03-04 16:57:59
【问题描述】:
我已经创建了一个单独的类来连接我的数据库,并且该类在一个单独的 PHP 文件中:
connect.php
class connect{
function __construct(){
// Connect to database
}
function query($q){
// Executing query
}
}
$connect = new connect();
现在,我创建了 $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 redeclare 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 中工作?
【问题讨论】:
-
除了不好的做法外,它应该可以工作。更好的方法是使用
new header($connect),例如注入依赖。 -
require_once('connect.php');在类头之外和global $connect;在头类的__construct()中.. -
@ahmet2106 forget
globalexists please -
但我会在
class header中使用__construct(connect $connect)并在您的主文件中定义$header = new header($connect);。所以只有requireconnect.php 和 header.php 在你的主文件顶部一次。 -
@Gordon 我不喜欢全球性的,是的,这是邪恶的,我知道 ;)
标签: php class require-once