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

I have the following two files, first is for config options, and the second contains some functions. When I try to get the variable from config.php in functions.php then I get error:

Notice: Undefined variable: config in /var/www/app/functions.php on line 15

Config in file config.php

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

File functions.php

require_once 'config.php';

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

When I tried to place the config variable inside the function it works correctly. Why I can do this my way?

function get_header() {

  global $config;

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

Basically, you're using global variable in a local context.

It would be a good idea to encapsulate config in some kind of Config class, with singleton, so the config does not get overwritten by anything.

To be totally compliant with almost good OOP practices ;)

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];

 }

}

and then in configs/templates.php

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

your function would look like this:

function get_header() {

  $config = ConfigManager::get('templates');

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

This may seem overly complicated, and of course you don't have to follow this kind of practices, but the more you code, the more you will enjoy good practices.

Using globals is not one of them!

You are INSIDE a function.

You can put $config as a global or you need to pass it to the function to have the data.

You're working inside a function, which is always tricky.

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