PHP包含和类范围

时间:2016-08-03 00:13:26

标签: php function class scope include

我在开发的脚本中遇到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;

感谢。

1 个答案:

答案 0 :(得分:0)

正如@RiggsFolly提到的那样,因为存在冲突的可能性,所以在课堂上提供全球性并不是一个好主意。使用它作为参数,动态变化,取决于调用它的方法/对象。

 function someMethod($db){
     var_dump($db);
  }

并且还将file2.php中的函数移动到类中的函数,如果此函数仅需要此类