データベースに接続するための別のクラスを作成しました。そのクラスは別の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で機能するのですか?