为什么不赞成在PHP中通过引用进行函数调用? [英] Why is function call by reference in PHP deprecated?

查看:149
本文介绍了为什么不赞成在PHP中通过引用进行函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码:

<?php
    $a1 = "WILLIAM";
    $a2 = "henry";
    $a3 = "gatES";

    echo $a1." ".$a2." ".$a3. "<br />";

    fix_names($a1, $a2, $a3);

    echo $a1." ".$a2." ".$a3;

    function fix_names(&$n1, &$n2, &$n3)
    {
        $a1 = ucfirst(strtolower(&$n1));
        $a2 = ucfirst(strtolower(&$n2));
        $a3 = ucfirst(strtolower(&$n3));

    }

    ?>

我收到此通知:不推荐使用:引用时传递呼叫时间已不推荐使用

I received this notice: Deprecated: Call-time pass-by-reference has been deprecated

我需要解释为什么我会收到此通知?为什么在PHP 5.3.13版中不推荐使用此功能?

I need an explanation why did I receive this notice? And why in PHP Version 5.3.13, this has been deprecated?

推荐答案

这全部记录在PHP

This is all documented on the PHP Passing by Reference manual page. Specifically (added emphasis mine):

注意:在函数调用上没有参考符号-仅在函数上 定义.仅函数定义就足以正确传递 通过引用的论点.从PHP 5.3.0开始,您将收到警告 说您使用&时不赞成使用通过引用传递时间" 在foo(& $ a);中.从PHP 5.4.0开始,调用时传递引用是 删除,因此使用它会引发致命错误.

Note: There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

因此,它在PHP 5.3.x中已被弃用(并会发出警告),而在PHP 5.4中将失败.

As such, it was deprecated (and will throw a warning) in PHP 5.3.x and will fail in PHP 5.4.

也就是说,这是一个微不足道的解决方案.只需按如下所示更新fix_names函数:

That said, it's a trivial fix. Simply update your fix_names function as follows:

function fix_names(&$n1, &$n2, &$n3)
{
    $a1 = ucfirst(strtolower($n1));
    $a2 = ucfirst(strtolower($n2));
    $a3 = ucfirst(strtolower($n3));

}

顺便说一句,5.3.x系列的牙齿越来越长,因此,如果可能的话,更新到较新的版本(在进行必要的测试之后)是明智的.

Incidentally, the 5.3.x series is getting quite long in the tooth, so it would be wise to update to a more recent build (after carrying out the necessary testing) if at all possible.

这篇关于为什么不赞成在PHP中通过引用进行函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆