2012-05-25 71 views
1

我要做到这一点:使用的参考值作为PHP函数的默认PARAM

/* example filename: config_load.php */ 

$config_file = "c:\path\to\file.php"; 

function read_config($file = &$config_file) 
{ 
$settings = array(); 
$doc = new DOMDocument('1.0'); 
$doc->load($file); 
$xpath = new DOMXPath($doc); 
$all=$xpath->query('appSettings/add'); 
foreach ($all as $setting) {$settings[$setting->getAttribute('key')]=$setting->getAttribute('value');} 

return $settings; 
} 

/* end config_load.php */ 

所以后来当我真正调用该文件,它会是这样的 -

require_once "config_load.php"; 
// $config_file = "c:\path\to\file2.php"; //could also do this 
$config = read_config(); 

这样,如果我不指定文件,它将读取默认配置文件。在我进行函数调用之前,我还可以在任何地方定义$ config_file。并且无法访问config_load文件的用户不必担心能够加载不同的文件,他们可以在进行read_config()调用之前将其定义在任何位置。

+0

问题是什么? – symcbean

+0

[如何将PHP函数的参数设置为默认值的变量]的可能重复(http://stackoverflow.com/questions/10731047/how-to-set-a-php-functions-param-to-a -variable-as-the-default-value/10731060) – vstm

回答

0

这是不可能:

默认值必须是常量表达式,而不是(例如)一个变量,类成员,或者一个函数调用。

http://www.php.net/manual/en/functions.arguments.php#functions.arguments.default

然而,让您可以这样说:

function read_config($file = false) { 
    global $config_file; 
    if ($file === false) $file = $config_file; 

    $settings = array(); 
    $doc = new DOMDocument('1.0'); 
    $doc->load($file); 
    $xpath = new DOMXPath($doc); 
    $all=$xpath->query('appSettings/add'); 
    foreach ($all as $setting) {$settings[$setting->getAttribute('key')]=$setting->getAttribute('value');} 

    return $settings; 
} 

或像这样:

function read_config($file = false, $config_file = false) { 
    if ($file === false && $config_file !== false) $file = $config_file; 

    $settings = array(); 
    $doc = new DOMDocument('1.0'); 
    $doc->load($file); 
    $xpath = new DOMXPath($doc); 
    $all=$xpath->query('appSettings/add'); 
    foreach ($all as $setting) {$settings[$setting->getAttribute('key')]=$setting->getAttribute('value');} 

    return $settings; 
} 
+0

所以我必须使用全局 - 这是唯一的方法来做到这一点? –

+0

添加说明+其他选项 – Jeroen

+0

任何想法,为什么我不能得到这个工作与常数?我试图定义(“CONFIG_FILE”,“C:\路径\ file.php”);函数read_config($ file = CONFIG_FILE){code};并用read_config()调用,并没有运气。常量似乎是更好的选择。 –