我在脚本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