我在腳本IAM開發中的var範圍有問題,現在我想我將不得不重寫所有的方法,但讓我們看看是否有人可以指向正確的方向。PHP包含和類範圍
file1.php
<?php
$db = new SystemDB();
include('file2.php');
someFile2Function();
?>
file2.php
<?php
function someFile2Function(){
$db = new Database;
include('class.php');
$class = new CustomClass();
$class->someMethod();
}
?>
class.php
<?php
class CustomClass {
function someMethod(){
global $db; <-- this var is the file1.php var and not the file2.php function var
// execute some query
}
}
?>
我的問題是,使用類變量$分貝內是一個在file1.php中,而不是file2.php中的someFile2Function()中的一個。
有沒有辦法使用全局$ db,它使用someFile2Function()上聲明的var $ db;
謝謝。
不要使用'globals'一樣,在班需要。它完全破壞了封裝。將它作爲參數傳遞給'someclass :: __ construct($ db)',並將其保存爲某個類的屬性 – RiggsFolly
我知道這是我的錯!我要求看看是否有一種方法,我不必重寫所有類和方法將$ db對象傳遞給構造函數。 – Galfau