2012-02-06 46 views
2

我是PHP新手,我有一個非常基本的問題。我想在我的項目的所有PHP文件中設置PEAR日誌記錄。我如何實現這一目標?現在,在每一個單一的文件中有以下幾行:如何設置包含目錄的所有PHP腳本?

// Repeated lines 
require_once 'Log.php'; 
$conf = array('mode' => 0600, 'timeFormat' => '%X %x'); 
$logger = Log::singleton('file', 'out.log', 'ident', $conf); 

// Some logging... 
$logger->log("Log entry"); 

重複3行似乎不是正確的解決方案。我實際上和我的Propel生成的類有相同的問題。我該如何解決這個問題?

馬丁

回答

3

我會使用一個全球包括文件,做所有你需要在每個頁面上做一般的東西。例如,如果你想要來實例記錄器,連接到數據庫,並執行與用戶的$_SESSION東西在每個頁面上,你可以創建一個全球包括:

在/includes/global.php

require_once 'Log.php'; 
$conf = array('mode' => 0600, 'timeFormat' => '%X %x'); 
$logger = Log::singleton('file', 'out.log', 'ident', $conf); 

// Connect to DB 

// Do $_SESSION stuff 
在/any/other/file.php

require_once('/includes/global.php'); 

// $logger is already defined: 
$logger->log("Log entry"); 

如果你需要登錄一個函數內部

,你可以抓住你單身的副本,或者使用global關鍵字:

function test($a) 
{ 
    global $logger; 
    $logger->log('test() - ' . $a); 
} 

編輯:最後,你可以使用php.ini directiveauto_prepend_file規定與在主文件之前自動解析的文件名。

0

將三條線移動到一個單獨的文件和require_once那一個。

文件 「MyLog.php」:

require_once 'Log.php'; 
$conf = array('mode' => 0600, 'timeFormat' => '%X %x'); 
$logger = Log::singleton('file', 'out.log', 'ident', $conf); 

其他文件:

require_once 'MyLog.php'; 
$logger->log("Log entry"); 
相關問題