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


Using reference value as default param in PHP Function

我想这样做:

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

这是不可能的:

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

~ 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;
}

是的,你可以:

<?php
$greet = function()
{
   return "Hello";
};
$a = $greet();
echo $a;
?>

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