Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is function call by reference in PHP deprecated?

I wrote the following code:

<?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

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

like image 925
Muhammad Maqsoodur Rehman Avatar asked Aug 04 '13 19:08

Muhammad Maqsoodur Rehman


People also ask

What does deprecated mean in PHP?

The deprecation indicates the feature in question may be removed in the future. This warning refers to a line like $obj =& new MyClass(); The ampersand is not required any more since php 5; you can simply write $obj = new MyClass();

Why do we need call by reference in PHP?

In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments. The & represents reference of the variable.

Does PHP pass by reference?

pass by reference. Clearly, PHP, like C++, is a language that does support pass by reference. By default, objects are passed by value.

What is deprecated in PHP 8?

When declaring a function or a method, adding a required parameter after optional parameters is deprecated since PHP 8.0. Need to check the code in the declaration of functions and methods and their calls.


1 Answers

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

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.

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

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));

}

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.

like image 110
John Parker Avatar answered Oct 02 '22 14:10

John Parker