PHP - 通过引用函数参数传递

时间:2012-10-01 16:05:01

标签: php function reference arguments

  

可能重复:
  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

我一直在尝试一些没有成功的事情。有什么方法可以实现这个目标吗?

1 个答案:

答案 0 :(得分:2)

不幸的是你无法做到这一点,解析器不能(不能!)满足在函数定义中解析变量。

但是,您可以在定义中使用&$hierarchy = null定义函数,并使用is_null查看是否传递了值。 (除非您的引用值有时为null,那么您将需要另一种解决方法)

如果is_null返回true,则可以指定$hierarchy = &$this->hierarchy


在PHP聊天中进行快速讨论之后,使用func_num_args()可能会有用。它不计算使用默认值填充的args,因此您可以通过引用安全地传递包含null的变量,并使用此函数来确定$hierarchy中的值是否来自传递的参数,或者默认情况下。 (感谢@NikiC)

相关问题