【问题标题】:PHP Notice: Undefined variable when including another file and getting variable from it in a functionPHP 注意:在函数中包含另一个文件并从中获取变量时未定义的变量
【发布时间】:2014-01-08 13:33:24
【问题描述】:

我有以下两个文件,第一个是配置选项,第二个包含一些功能。当我尝试从functions.php 中的config.php 获取变量时,出现错误:

注意:未定义变量:/var/www/app/functions.php 第 15 行中的配置

config.php 文件中的配置

$config = array('page_title' => 'Page Title');

文件函数.php

require_once 'config.php';

function get_header() {
  $header = new Template( 'header' );
  $header->set( 'pagetitle', $config['page_title'] );
  echo $header->output();
}

当我尝试将配置变量放在函数中时,它可以正常工作。为什么我可以这样做?

【问题讨论】:

    标签: php variables undefined require


    【解决方案1】:
    function get_header() {
    
      global $config;
    
      $header = new Template( 'header' );
      $header->set( 'pagetitle', $config['page_title'] );
      echo $header->output();
    }
    

    基本上,您在本地上下文中使用全局变量。

    最好将配置封装在某种 Config 类中,使用单例,这样配置就不会被任何东西覆盖。

    完全符合几乎良好的 OOP 实践;)

    class Config {
    
     protected $data;
    
     public function __construct(array $config) {
    
      $this->data = $config;
    
     }
    
     public function get($key) {
    
      return $this->data['key'];
    
     }
    
    }
    
    
    class ConfigManager {
    
     public static $configs;
    
     // In "good OOP" this should't be static. ConfigManager instance should be created in some kind of initialisation (bootstrap) process, and passed on to the Controller of some sort
     public static function get($configName) {
    
      if(! isset(self::$configs[$configName]))
       self::$configs[$configName] = new Config(include('configs/' . $configName. '.php')); // in good OOP this should be moved to some ConfigReader service with checking for file existence etc
    
      return self::$configs[$configName];
    
     }
    
    }
    

    然后在configs/templates.php

    return array('page_title' => 'Page Title');
    

    你的函数应该是这样的:

    function get_header() {
    
      $config = ConfigManager::get('templates');
    
      $header = new Template( 'header' );
      $header->set( 'pagetitle', $config->get('page_title') );
      echo $header->output();
    }
    

    这可能看起来过于复杂,当然您不必遵循这种做法,但是您编写的代码越多,您就会越喜欢好的做法。

    使用全局变量不是其中之一!

    【讨论】:

      【解决方案2】:

      你在一个函数内部。

      您可以将 $config 作为全局变量,或者您需要将其传递给函数以获取数据。

      【讨论】:

        【解决方案3】:

        您在函数内部工作,这总是很棘手。

        function get_header() {
         global $config; //this will fix it
         $header = new Template( 'header' );
         $header->set( 'pagetitle', $config['page_title'] );
         echo $header->output();
        }
        

        【讨论】:

          猜你喜欢
          • 2017-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-18
          • 2010-12-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多