2014-01-08 41 views
1

我有以下兩個文件,第一個用於配置選項,第二個包含一些函數。當我嘗試從config.php得到變量functions.php然後我得到錯誤:PHP注意:當包含另一個文件並從函數中獲取變量時未定義的變量

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

配置文件的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(); 
} 

當我試圖將配置變量放置在它正常工作的函數中。爲什麼我能按我的方式做到這一點?

回答

2
function get_header() { 

    global $config; 

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

基本上,你在本地上下文中使用全局變量。

將配置封裝在某種Config類中,使用singleton是一個好主意,所以配置不會被任何東西覆蓋。

爲了與幾乎良好的面向對象的做法完全兼容;)

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設置爲全局或您需要將它傳遞給函數以獲取數據。

1

你在一個函數裏面工作,這總是很棘手。

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