crunchy crunchy - 2 months ago 8
PHP Question

PHP what does the "&" mean in the function-parameter?

I saw a sorting-function like:

function aasort (&$array, $key) { ... }


what does this
&
in
&$array
exactly mean?

Answer

It is a reference to a variable. Instead of passing the value of the variable it passes the location of the variable.

   <?php
    function add_some_extra(&$string)
    {
        $string .= 'and something extra.';
    }
    $str = 'This is a string, ';
    add_some_extra($str);
    echo $str;    // outputs 'This is a string, and something extra.'
    ?>

Basically think of a variable as a container of a value. When arguments for a function are created like: function fun($param, $param2) and variables are passed into it like: fun($var1, $var2) the function is given the values of the containers $var1 and $var2 for $param and $param2

However when arguments are defined like: function fun(&$theParty) and run like fun($atMyHouse) then the location of $atMyHouse (the container) is passed so any changes made to the argument will also change the value in the variable of $atMyHouse

http://php.net/manual/en/functions.arguments.php

Comments