簡體   English   中英

PHP注意:在函數中包含另一個文件並從中獲取變量時,未定義的變量

[英]PHP Notice: Undefined variable when including another file and getting variable from it in a function

我有以下兩個文件,第一個用於配置選項,第二個包含一些功能。 當我嘗試從functions.php config.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變量放在函數內時,它可以正常工作。 為什么我可以做到這一點?

您在一個函數中。

您可以將$ config設置為全局變量,或者需要將其傳遞給函數以獲取數據。

function get_header() {

  global $config;

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

基本上,您是在局部上下文中使用全局變量。

用單例將config封裝在某種Config類中是個好主意,這樣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();
}

這似乎過於復雜,當然您不必遵循這種做法,但是您編寫的代碼越多,您就會越享受良好的做法。

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

您正在一個函數內部工作,這總是很棘手的。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM