【问题标题】:Include a file in a class in PHP在 PHP 的类中包含文件
【发布时间】:2011-10-26 17:52:03
【问题描述】:

是否可以在类中包含带有 PHP 变量的文件?什么是最好的方法,以便我可以访问整个班级的数据?

我已经在谷歌上搜索了一段时间,但没有一个示例有效。

【问题讨论】:

标签: php class variables include


【解决方案1】:

最好的方法是加载它们,而不是通过外部文件包含它们。

例如:

// config.php
$variableSet = array();
$variableSet['setting'] = 'value';
$variableSet['setting2'] = 'value2';

// Load config.php ...
include('config.php');
$myClass = new PHPClass($variableSet);

// In a class you can make a constructor
function __construct($variables){ // <- As this is autoloading, see http://php.net/__construct
    $this->vars = $variables;
}
// And you can access them in the class via $this->vars array

【讨论】:

    【解决方案2】:

    其实你应该给变量追加数据。

    <?php
        /*
            file.php
    
            $hello = array(
                'world'
            )
        */
    
        class SomeClass {
            var bla = array();
            function getData() {
                include('file.php');
                $this->bla = $hello;
            }
    
            function bye() {
                echo $this->bla[0]; // Will print 'world'
            }
        }
    ?>
    

    【讨论】:

      【解决方案3】:

      从性能的角度来看,最好使用 .ini 文件来存储设置。

      [db]
      dns      = 'mysql:host=localhost.....'
      user     = 'username'
      password = 'password'
      
      [my-other-settings]
      key1 = value1
      key2 = 'some other value'
      

      然后在你的课堂上你可以做这样的事情:

      class myClass {
          private static $_settings = false;
      
          // This function will return a setting's value if setting exists,
          // otherwise default value also this function will load your
          // configuration file only once, when you try to get first value.
          public static function get($section, $key, $default = null) {
              if (self::$_settings === false) {
                  self::$_settings = parse_ini_file('myconfig.ini', true);
              }
              foreach (self::$_settings[$group] as $_key => $_value) {
                  if ($_key == $Key)
                      return $_value;
              }
              return $default;
          }
      
          public function foo() {
              $dns = self::get('db', 'dns'); // Returns DNS setting from db
                                             // section of your configuration file
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-02
        • 2012-02-13
        • 2016-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多