如何回溯默认函数参数?

时间:2011-07-03 18:36:55

标签: php

function backtrace() {
    var_dump(debug_backtrace());
}


function echosth($what = 'default text') {
    echo $what;
    backtrace();
}

echosth('another text'); //argument is shown 
                         // ["args"]=> array(1) {[0]=>&string(12) "another text"}
echosth(); //it appears as function has none arguments ["args"]=>array(0) {}

有没有办法获得父函数的默认值?

2 个答案:

答案 0 :(得分:3)

是的,通过PHP反射类的getDefaultValue

function foo($test, $bar = 'baz')
{
    echo $test . $bar;
}

$function = new ReflectionFunction('foo');

foreach ($function->getParameters() as $param) {
    echo 'Name: ' . $param->getName() . PHP_EOL;
    if ($param->isOptional()) {
        echo 'Default value: ' . $param->getDefaultValue() . PHP_EOL;
    }
    echo PHP_EOL;
}

既然您了解了debug_backtrace,那么您应该能够获取调用函数的名称并通过该循环运行它。

答案 1 :(得分:2)