0

データベースに接続するための別のクラスを作成しました。そのクラスは別の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");
    }

}

なぜheader.phpではなくindex.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 に答える