【问题标题】:PHP Include and Class ScopePHP 包含和类范围
【发布时间】: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


【解决方案1】:

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

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

如果只有这个类需要这个函数,也宁愿将file2.php中的函数移到类中的函数

【讨论】:

  • 我创建了 file2.php 函数只是为了尝试使用该类的函数范围,但这似乎不起作用。
猜你喜欢
  • 1970-01-01
  • 2014-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
  • 2014-11-27
  • 1970-01-01
相关资源
最近更新 更多