【问题标题】:Scope issue: required file cant access variables when called in class范围问题:在类中调用所需文件时无法访问变量
【发布时间】:2011-12-11 06:08:19
【问题描述】:
$test = test;

class getFile{
    public function __construct($fileName){
    require $fileName;
  } 
}

$get = new getFile('file.php');

所以file.php包含,echo $test;

如果我要在课堂外调用它,例如

需要'test.php';它会得到 $test 罚款 但是在类内部调用有明显的范围问题。如何让函数中所需的文件访问变量?

编辑:------------

我有多个变量我希望这个文件可以访问(它们都是基于页面的动态变量,因此添加 x 和 y 变量是不可能的,因为它们不会总是被设置)而不是将每个变量声明为全局可访问的,是没有办法允许类中的所需文件访问这些变量,就好像它不是一样?

感谢大家的反馈。不幸的是,我想要的似乎不太可能,但您启发了我创建一个解决方法,将我需要文件访问的最重要变量注册为全局变量。

【问题讨论】:

  • 将变量添加到方法范围

标签: php class object require scopes


【解决方案1】:
public function __construct($fileName) {
    global $test;
    require $fileName;
} 

会起作用

【讨论】:

  • 也许我还不够清楚,我有成千上万个文件我希望这个文件可以访问。例如文件:1,2,3,4 + 设置了所有变量,并且该文件需要访问它们 - 这种方法对于这么大的东西是不切实际的。
  • @BillyJakeO'Connor 请查看我对这个问题的第二个答案
【解决方案2】:

也许你可以在你的类中声明一个全局变量,像这样:

$text = 'test';

class getFile {
   public function __construct($fileName) {
      global $test;
      require $fileName;
   }
}

$get = new getFile('file.php');

【讨论】:

    【解决方案3】:

    在全局范围内声明的 PHP 变量不会自动在函数或方法中可用。您必须明确声明它们是全局变量:

    file.php:
    
        <?php
        global $test
        echo $test
    

    public function __construct($filename) {
        global $test;
        require $filename;
    }
    

    都可以解决问题。即使file.php 脚本看起来是全局的,因为其中没有函数定义,它仍然绑定到对象中__construct() 方法的范围,它不会有 $test 全局。

    【讨论】:

      【解决方案4】:

      回复您的评论,我有您可能喜欢的解决方法

      class getFile{
          public $files = Array();
          public function __construct($fileName){
              $this->files[] = $fileName;
          } 
      }
      
      $get = new getFile('file.php');
      
      foreach($get->files as $file) require($file);
      

      或者你可以创建静态方法?

      class getFile{
          public static $files = Array();
          public static function get($fileName){
              self::$files[] = $fileName;
          } 
      }
      
      getFile::get('file1.php');
      getFile::get('file2.php');
      getFile::get('file3.php');
      
      foreach(getFile::$files as $file) require($file);
      

      【讨论】:

      • 严格标准:非静态方法 PEAR::registerShutdownFunc() 不应该被静态调用:/ 抱歉,伙计,但它不能正常工作。
      猜你喜欢
      • 1970-01-01
      • 2015-09-07
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      • 2010-11-16
      • 2018-04-08
      相关资源
      最近更新 更多