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

标签 php function reference arguments

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/

相关文章:

php - WooCommerce 预订 : Retrieve the booking data before order is created

python - 从excel调用python函数

PHP 反射方法 > 无法返回引用

c++ - sf::Sprite 是白色矩形(纹理试图通过引用传递)

javascript - 存储对 DOM 元素的引用

php - 获取第二个表的计数以及 id

php - 计算表中唯一数据的数量

php - 如何在 php 文件中编写 css 类?

JAVA 如何将全局变量放入函数参数中?

c++ - 应该如何编写计算到点的最近距离的 C++ 函数?