0

我已经创建了一个单独的类来连接到我的数据库,并且该类位于一个单独的 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 中工作?

4

1 回答 1

2

您的问题可能是在使用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");
        }

    }
于 2012-02-13T09:32:13.420 回答