我制作了一个单独的类来连接到我的数据库,并且该类在单独的PHP文件中:
class connect{
function __construct(){
// Connect to database
}
function query($q){
// Executing query
}
}
$connect = new connect();
现在,我制作了$ connect类的对象,并在index.php之类的文件中使用它时起作用:
require_once('connect.php');
$set = $connect->query("SELECT * FROM set");
现在,在这里工作正常,我不必为该类重新创建对象并直接执行查询,而在另一个名为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中起作用?
require_once()
而不是require()
。首次包含connect.php
时,它工作良好,因为已初始化变量并装入了类,但是稍后再次尝试时,require_once()
禁止重复包含,因此未初始化任何变量。无论如何,在构造函数内部使用include()
是...很少有道理的。并且包含一个将初始化局部变量的文件也是个坏主意。
正确的代码如下:
<?php
require_once('connect.php');
require_once('header.php');
$connect = new Connect();
$header = new Header($connect);
和header.php
:
<?php class Header{ protected $connection = null; function __construct(Connect $connection){ $this->connection = $connection; $res = $this->connection->query("SELECT * FROM table"); } }