例えば、database.php、parent.php、child1.php、child2.php、somescript.phpの5つのスクリプトがあるとします。
parent.phpのクラスは以下のようになっています。
include 'database.php';
class Parent {
public $db;
function __construct() {
$this->db = new Database();
}
}
child1 と child2 クラスは次のようになります。
include 'parent.php';
class Child1 extends Parent {
function __construct() {
parent::__construct();
}
function useDb() {
$this->db->some_db_operation();
}
}
問題点)
somescript.phpにchild1とchild2の両方を入れようとすると、以下のようなエラーが返ってきます。
cannot declare class Database because the name is already in use in a database.php on line 4 (この行には 'class が含まれています) cannot declare class Database because the name is already in use in in the database.php on line 4 (this is the line which contains words 'class Database')*。
しかし、1つのファイル(child1またはchild2)だけをインクルードすると、うまく動作します。
どのように修正すればよいでしょうか?
その場合は、include_once()または[require_once()][2]を使用してください。もうひとつの方法は、クラスのインクルードをすべて正しい順序で記述した追加ファイルを作成し、インクルード自体を呼び出す必要がないようにすることです。
"classes.php"
include 'database.php';
include 'parent.php';
include 'child1.php';
include 'child2.php';
ならば、必要なのは
require_once('classes.php');
私は以前この問題を抱えていましたが、これを解決するには 確認してください。
1.このクラスのインスタンスを作成していないこと 2.クラスメソッドからこれを呼び出した場合、呼び出したクラスに__destructが設定されていることを確認してください。
私の問題(以前): Core、Router、Permissions、Renderというクラスがあります。 CoreはRouterクラスを含み、RouterはPermissionsクラスを呼び出し、Routerの__destructはRenderクラスを呼び出し、エラー"Cannot declare class because the name is already in use"が表示されました。
解決方法 Permissionクラスにdestructを追加して、destructが空になったので、直りました...。