PHP注意:包含另一个文件并在函数中从中获取变量时的未定义变量

时间:2014-01-08 13:33:24

标签: php variables undefined require

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

  

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

配置文件config.php

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

文件functions.php

require_once 'config.php';

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

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

3 个答案:

答案 0 :(得分:2)

你是一个职能部门。

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

答案 1 :(得分:2)

function get_header() {

  global $config;

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

基本上,您在本地环境中使用全局变量。

将config配置在某种Config类中是个好主意,使用singleton,因此配置不会被任何东西覆盖。

完全符合几乎好的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 :(得分:1)

你在一个函数内部工作,这总是很棘手。

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