在PHP函数中使用引用值作为默认参数

时间:2012-05-25 13:14:57

标签: php function dom reference default

我希望这样做:

/* 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()调用之前在任何地方定义它。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:-1)

是的,你可以:

<?php

$greet = function()
{
   return "Hello";
};

$a = $greet();
echo $a;
?>

在这里阅读更多内容: http://php.net/manual/en/functions.anonymous.php