PHP函数参数之引用传递

来源:互联网 发布:软件ac控制器 编辑:程序博客网 时间:2024/05/20 23:29

PHP函数参数之引用传递

与c/c++类似,PHP函数也提供了参数引用传递功能来避免对象的复制,以及可以通过引用参数返回处理结果(不推荐该方式,一般可以将结果打包返回)

问题:假设目前已经有一个函数foo,其返回值也已经确定,为了增加一个返回值,而且还不想修改现有的对返回值的处理逻辑,我可以为函数增加一个引用参数,来达到目的。

现有的函数定义:

<?phpfunction foo($first,$second = 'new'){  return first;}
修改后:

<?phpfunction foo($first,$second = 'new',&$third){    if ($second != 'new'){        $third = false;    }       else        $third = true;    return first;}

测试代码如下:

<?phpfunction foo($first,$second='new',&$third){    if ($second != 'new'){        $third = false;    }    else        $third = true;    return $first;}$third = true;foo("test1");echo "third: " . $third . "\n";  // 未改变foo("test2",'good');echo "third: " . $third . "\n";  // 未改变$third = true;foo("test3",'good',$third);if ($third)    echo "third: true\n";else    echo "third: false\n";foo("test4");if ($third)    echo "third: true\n";else    echo "third: false\n";?>

测试结果如下:
third: 1
third: 1
third: false
third: false


结果分析:
只有当我们传入$third变量后,主函数中的$third变量中的值才为函数返回的处理结果
另,当引用参数为最后一个变量时,可以不用传入任何参数,当然这样也就不会传出任何值
参考文档:
http://www.php.net/manual/en/language.references.pass.php