我已经创建了一个单独的类来连接到我的数据库,并且该类位于一个单独的 PHP 文件中:
连接.php
class connect{
function __construct(){
// Connect to database
}
function query($q){
// Executing query
}
}
$connect = new connect();
现在,我创建了 $connect 类的对象,当在 index.php 之类的文件中使用它时,它可以工作:
索引.php
require_once('connect.php');
$set = $connect->query("SELECT * FROM set");
现在,在这里它工作正常,我不必为类重新创建对象并直接执行查询,而在另一个名为 header.php 的文件中,我有一个这样的类:
头文件.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 中工作?