函数中的参考参数(& $ a),好还是坏?

时间:2012-04-11 10:08:58

标签: php function parameter-passing pass-by-reference

我们编写了两个验证函数,一个如下(它一次获取所有字段):

function check_fields(&$arr,&$msg,$types,$lens,$captions,$requireds) {}

,另一个功能如下:

function is_valid($field=NULL,$type=0 ,$length=0,$required=true) {}

第一个函数有一些代码行,并且显着减少了代码行(大约30-35行甚至更多),另一方面没有引用的第二个函数增加了代码行(大约30-35行甚至更多)

我们必须为我们想要验证的每个字段调用第二个函数,但第一个函数(check_fields)反之亦然。 我很久以前在一篇文章中读到,从性能的角度来看,参考参数的函数是不好的。

现在我们不知道要使用哪个函数。从绩效角度来看哪一个更好?

3 个答案:

答案 0 :(得分:1)

使用更易于使用且更易于维护的解决方案。 你在谈论微优化,这几乎没用。

<小时/> 使用引用,因为在您的情况下,它是更简单的解决方案,需要更少的代码。

答案 1 :(得分:1)

嗯,我想在网上搜索后我自己得到了答案:

Do not use PHP references

答案 2 :(得分:0)

当你打电话时,你只记得这个:

   <?php 
    $a = 1 ;
    echo "As initial, the real 'a' is..".$a."<br/>";
    $b = &$a ; // it's meaning $b has the same value as $a, $b = $a AND SO $a = $b (must be)
    $b += 5;
    echo "b is equal to: ".$b." and a equal to: ".$a."<br/>";
    echo " Now we back as initial, when a=1... (see the source code) <br/>";
    $a = 1 ;
    echo "After we back : b is equal to: ".$b." and a equal to: ".$a."<br/>";
    echo "Wait, why b must follow a? ... <br/> ..what about if we change b alone? (see the source code)<br/>";
    $b = 23; 
    echo "After we change b alone, b equal to: ".$b." and a equal to: ".$a."<br/>";
    echo " WHAT ?? a ALSO CHANGED ?? a and b STICK TOGETHER?!! </br>" ;
    echo "to 'clear this, we use 'unset' function on a (see the source code)<br/> ";
    unset($a);
    $b = 66;
    $a = 1;
    echo "Now, after unset,b is equal to: ".$b." and a equal to: ".$a."<br/>"; 
    ?>

输出将是:

As initial, the real 'a' is..1
After the Reference operator...(see the source code)
b is equal to: 11 and a equal to: 11
Now we back as initial... (see the source code) 
After we back : b is equal to: 1 and a equal to: 1
Wait, why b must follow a? ... 
..what about if we change b alone? (see the source code)
After we change b alone, b equal to: 23 and a equal to: 23
WHAT ?? a ALSO CHANGED ?? a and b STICK TOGETHER?!! 
to 'clear this, we use 'unset' function on a (see the source code)
Now, after unset,b is equal to: 66 and a equal to: 1

修改:

$a为什么会改变?这是因为&(和号运算符)将&作为参考变量,因此它存储在一个临时存储器中。在初始化$b= &$a时,请参阅我的评论$b = $a 以及 $a = $b,这意味着每当您修改$b时,$a也是修改,反之亦然。 他们被链接!这就是参考运算符的简单含义。

也许在开始时感觉很混乱,但是一旦你成为这方面的专家,你就可以处理这个操作员来做一个&#34;切换&#34;功能如下:

<?php

function bulbswitch(&$switch)
{
    $switch = !$switch;    

}

function lightbulb($a)
{
    if ($a == true) { echo 'a is On <br/>';}
    else { echo 'a is Off <br/>';}
}

$a = true ;
echo 'At the begining, a is On, then.... <br/>';

bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
bulbswitch($a);
lightbulb($a);
?>

输出将是:

At the begining, a is On, then.... 
a is Off 
a is On 
a is Off 
a is On 
a is Off 
a is On