PHP函数参数之引用传递
PHP函数参数之引用传递
与c/c++类似,PHP函数也提供了参数引用传递功能来避免对象的复制,以及可以通过引用参数返回处理结果(不推荐该方式,一般可以将结果打包返回)
问题:假设目前已经有一个函数foo,其返回值也已经确定,为了增加一个返回值,而且还不想修改现有的对返回值的处理逻辑,我可以为函数增加一个引用参数,来达到目的。
现有的函数定义:
<?php
function foo($first,$second = "new")
{
return first;
}修改后:
<?php
function foo($first,$second = "new",&$third)
{
if ($second != "new"){
$third = false;
}
else
$third = true;
return first;
}测试代码如下:
<?php
function foo($first,$second="new",&$third)
{
if ($second != "new"){
$third = false;
}
else
$third = true;
return $first;
}
$third = true;
foo("test1");
echo "third: " . $third . "
"; // 未改变
foo("test2","good");
echo "third: " . $third . "
"; // 未改变
$third = true;
foo("test3","good",$third);
if ($third)
echo "third: true
";
else
echo "third: false
";
foo("test4");
if ($third)
echo "third: true
";
else
echo "third: false
";
?>测试结果如下:
third: 1
third: 1
third: false
third: false
结果分析:
只有当我们传入$third变量后,主函数中的$third变量中的值才为函数返回的处理结果
另,当引用参数为最后一个变量时,可以不用传入任何参数,当然这样也就不会传出任何值
参考文档:
http://www.php.net/manual/en/language.references.pass.php
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 随机打乱一个数组(输出无序数组)
- 下一篇: PHP 函数的引用传递(地址传递&)问题
