1

我正在寻找这样做:

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

4

2 回答 2

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;
}
于 2012-05-25T13:20:41.797 回答
-1

是的你可以:

<?php

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

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

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

于 2012-05-25T13:46:21.350 回答