【发布时间】:2016-12-08 12:20:27
【问题描述】:
我正在开发的脚本中的 var 范围有问题,现在我想我将不得不重写我所有的方法,但让我们看看是否有人能指出我正确的方向。
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
}
}
?>
我的问题是,在类内部,正在使用的 var $db 是 file1.php 中的那个,而不是 file2.php 中 someFile2Function() 中的那个。
有没有办法使用全局 $db,它使用在 someFile2Function() 上声明的 var $db;
谢谢。
【问题讨论】:
-
不要像在课堂上那样使用
globals。它完全破坏了封装。将其作为参数传递给someclass::__construct($db)并将其保留为某个类的属性 -
我知道这是我的错!我想看看是否有一种方法我不必重写所有类和方法来将 $db 对象传递给构造函数。
标签: php function class scope include