Learn why your current code that uses the func_get_arg function may end up with different results when upgrading from PHP 5.x to 7.x

How the PHP functions "func_get_arg" and "func_get_args" changed from PHP 5.x to PHP 7.x

Upgrading the version of PHP for your project isn't usually complicated unless you have a lot of deprecated code in your project that was removed in the newest version. One of the things that many developers don't expect on change of version with minor builts e.g from 5.20 to 5.29, is the change of the behaviour of a built-in function, however with a major build, namely the new PHP 7, you may expects that some things may broke. In this case the func_get_arg function changed slightly. To understand how the function behaviour changed, analyze the following PHP snippet:


function printValue($value) {
    // Update value variable
    $value = "The value is: " . $value;

    // Print the value of the first argument
    echo func_get_arg(0);

// Run function

The function printValue will print the first argument sent to the function thanks to the func_get_arg function. If you run the code on different PHP versions, the output will be different. In PHP <=5.x, the output will be:


However, in PHP >=7.x, the output will be:

The value is: 123

But, why?

From now on in PHP 7.x, the functions func_get_arg and func_get_args won't return the original value that was providen as parameter, instead it will provide the current value of the argument (which may obviously have been modified by your own code intentionally). If the runtime of your function doesn't modify the value of the argument, then you don't have to worry about this little issue. Alternatively, you may fix this behaviour by simply creating a new variable in the scope that stores the same value of the argument but with the modification or make the modification after you retrieve its original value into another variable:


function printValue($value) {
    // Stores the modified value (2)
    $modifiedValue = $value + 1;
    echo func_get_arg(0);

// In any PHP prints: 1

Happy coding !

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.