Possible Duplicate:
default method argument with class property?
我正在编写一个递归函数,只是为了便于使用,我希望该函数的第一次调用接受默认参数。该值必须是对象成员变量的地址。完整代码见下面:
class Test{
public $hierarchy = array( );
public function addPath( $path, &$hierarchy ){
$dirs = explode( '/', $path );
if( count( $dirs ) == 1 ){
if( is_dir( $path ) )
$hierarchy[ $dirs[ 0 ] ] = '';
else
$hierarchy[ $path ] = '';
return $hierarchy;
}
$pop = array_shift( $dirs );
$hierarchy[ $pop ] = $this->addPath(
implode( '/', $dirs ), $hirearchy[ $pop ] );
return $hierarchy;
}
}
$t = new Test( );
$t->addPath( '_inc/test/sgsg', $t->hierarchy );
print_r( $t->hierarchy );
现在,我想要在这里做的理想情况是添加一个默认值:
public function addPath( $path, &$hierarchy = $this->hierarchy ){
这样我就可以这样调用它:
$t->addPath( '_inc/test/sgsg' );
但这给了我以下错误:
Parse error: syntax error, unexpected '$this' (T_VARIABLE) in tst.php on line 9
我一直在尝试一些事情,但没有成功。有什么办法可以实现这个目标吗?
最佳答案
不幸的是你不能这样做,解析器不(不能!)满足函数定义中解析变量的需求。
但是,您可以在定义中使用 &$hierarchy = null
定义函数,并使用 is_null
查看是否传递了值。 (除非您的引用值有时为空,否则您将需要另一种解决方法)
如果is_null
返回true,那么您可以分配$hierarchy = &$this->hierarchy
在 PHP 聊天中进行快速讨论后,使用 func_num_args()
在这里可能会有用。它不计算填充默认值的参数,因此您可以通过引用安全地传递包含 null
的变量,并使用此函数确定 $hierarchy
中的值是否为空。来自传递的参数,或默认的。 (感谢@NikiC)
关于PHP - 通过引用函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12676909/