0

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

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) 反之亦然。我很久以前在一篇文章中读到,从性能的角度来看,具有引用参数的函数很糟糕。

现在我们不知道该使用哪个函数。从性能的角度来看,哪个更好?

4

3 回答 3

1

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


使用引用,因为在您的情况下,它是更简单的解决方案并且需要更少的代码。

于 2012-04-11T13:33:40.063 回答
1

好吧,我想在一些网络搜索后我自己得到了答案:

不要使用 PHP 引用

于 2012-04-12T05:16:36.750 回答
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也被修改,反之亦然。他们被锁链了!这就是引用运算符的简单含义。

刚开始可能会觉得很困惑,但是一旦你成为这方面的专家,你就可以处理这个操作符来做一个这样的“切换”功能:

<?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
于 2016-03-21T17:10:58.000 回答