PHP类无法访问包含的变量

时间:2013-08-29 03:30:19

标签: php variables include scope

这是一个PHP新手问题:

我想让我的类访问包含文件中的数据库凭据:../ config.inc

<?php
   $db_info['host']='localhost'; // and so forth 
   ...
 ?>

稍后,在我的类源文件中,我有:

   <?php
      require_once('../config.inc'); // include the above file
      public class Foo {
         static function Host() {
            echo $db_info['host'];
         }
      }
   ?>

当尝试在其他代码中访问该类时,我收到一个错误,声称$ db_info未定义。当我尝试在类范围内移动require_once时(在Foo {之后)我得到语法错误,所以显然不能在类中使用require_once。编写需要访问包含数据的类静态方法时,最佳做法是什么?感谢。

1 个答案:

答案 0 :(得分:2)

您的范围存在问题。您所包含的变量可在课堂外使用,但不在课堂内。建议的方法应该是将变量传递给类的构造函数并将其存储在类的成员变量中。

但是由于您将该函数用作静态,因此您可以使用global,但这不是最佳实践。或者,您可以在函数中包含该文件。

  public class Foo {
     static function Host() {
      require_once('../config.inc'); // include the above fil  
      echo $db_info['host'];
     }
  }
相关问题