PHP Conference Nagoya 2025

Pasar por Referencia

Se puede pasar una variable por referencia a una función y así hacer que la función pueda modificar la variable. La sintaxis es la siguiente:

<?php
function foo(&$var)
{
$var++;
}

$a=5;
foo($a);
// $a es 6 aquí
?>

Nota: No existe ningún signo de referencia en una llamada a una función - sólo en la definición de la función. Las definiciones de funciones por sí solas son suficientes para pasar correctamente el argumento por referencia. A partir de PHP 5.3.0, se obtendrá una advertencia diciendo que "call-time pass-by-reference" (pasar por referencia en tiempo de llamada) está obsoleto cuando se use & en foo(&$a);. A partir de PHP 5.4.0, el paso por referencia en tiempo de llamada ha sido eliminado, por lo que su uso emitirá un error fatal.

Se puede pasar por referencia lo siguiente:

  • Variables, esto es, foo($a)
  • Referencias devueltas desde funciones, esto es:

    <?php
    function foo(&$var)
    {
    $var++;
    }
    function &
    bar()
    {
    $a = 5;
    return
    $a;
    }
    foo(bar());
    ?>
    Vea más sobre devolver por referencia.

Ninguna otra expresión debería pasarse por referencia, ya que el resultado no está definido. Por ejemplo, los siguientes ejemplos de pasar por referencia no son válidos:

<?php
function foo(&$var)
{
$var++;
}
function
bar() // Observe que falta el &
{
$a = 5;
return
$a;
}
foo(bar()); // Produce un error fatal a partir de PHP 5.0.5,un aviso de estándar estricto
// a partir de PHP 5.1.1, y un aviso a partir de PHP 7.0.0

foo($a = 5); // Expresión, no una variable
foo(5); // Produce un error fatal

class Foobar
{
}

foo(new Foobar()) // Produce un aviso a partir de PHP 7.0.7
// Observación: Solo las variables deben pasarse por referencia
?>

add a note

User Contributed Notes 5 notes

up
448
tnestved at yahoo dot com
10 years ago
By removing the ability to include the reference sign on function calls where pass-by-reference is incurred (I.e., function definition uses &), the readability of the code suffers, as one has to look at the function definition to know if the variable being passed is by-ref or not (I.e., potential to be modified). If both function calls and function definitions require the reference sign (I.e., &), readability is improved, and it also lessens the potential of an inadvertent error in the code itself. Going full on fatal error in 5.4.0 now forces everyone to have less readable code. That is, does a function merely use the variable, or potentially modify it...now we have to find the function definition and physically look at it to know, whereas before we would know the intent immediately.
up
29
ccb_bc at hotmail dot com
5 years ago
<?php
// PHP >= 5.6

// Here we use the 'use' operator to create a variable within the scope of the function. Although it may seem that the newly created variable has something to do with '$x' that is outside the function, we are actually creating a '$x' variable within the function that has nothing to do with the '$x' variable outside the function. We are talking about the same names but different content locations in memory.
$x = 10;
(function() use (
$x){
$x = $x*$x;
var_dump($x); // 100
})();
var_dump($x); // 10

// Now the magic happens with using the reference (&). Now we are actually accessing the contents of the '$y' variable that is outside the scope of the function. All the actions that we perform with the variable '$y' within the function will be reflected outside the scope of this same function. Remembering this would be an impure function in the functional paradigm, since we are changing the value of a variable by reference.
$y = 10;
(function() use (&
$y){
$y = $y*$y;
var_dump($y); // 100
})();
var_dump($y); // 100
?>
up
37
mike at eastghost dot com
9 years ago
beware unset() destroys references

$x = 'x';
change( $x );
echo $x; // outputs "x" not "q23" ---- remove the unset() and output is "q23" not "x"

function change( & $x )
{
unset( $x );
$x = 'q23';
return true;
}
up
2
Anonymous
1 year ago
Parameters passed by references can have default values.
You can find out if a variable was actually passed by using func_num_args():

<?php

function refault( & $ref = 'Do I have to be calculated?'){
echo
'NUM ARGS: '. func_num_args()."\n";
echo
"ORI VALUE: {$ref}\n";
if(
func_num_args() > 0 ) $ref = 'Yes, expensive to calculate result: ' . sleep(1);
else
$ref = 'No.';
echo
"NEW VALUE: {$ref}\n";
}

$result = 'Do I have to be calculated?';
refault( $result );
echo
"RESULT: {$result}\n";
// NUM ARGS: 1
// ORI VALUE: Do I have to be calculated?
// NEW VALUE: Yes, expensive to calculate result: 0
// RESULT: Yes, expensive to calculate result: 0

refault();
// NUM ARGS: 0
// ORI VALUE: Do I have to be calculated?
// NEW VALUE: No.
?>
up
2
Jason Steelman
5 years ago
Within a class, passing array elements by reference which don't exist are added to the array as null. Compared to a normal function, this changes the behavior of the function from throwing an error to creating a new (null) entry in the referenced array with a new key.

<?php

class foo {
public
$arr = ['a' => 'apple', 'b' => 'banana'];
public function
normalFunction($key) {
return
$this->arr[$key];
}
public function &
referenceReturningFunction($key) {
return
$this->arr[$key];
}
}

$bar = new foo();
$var = $bar->normalFunction('beer'); //Notice Error. Undefined index beer
$var = &$bar->referenceReturningFunction('beer'); // No error. The value of $bar is now null
var_dump($bar->arr);
/**
[
"a" => "apple",
"b" => "banana",
"beer" => null,
],
*/

?>
This is in no way a "bug" - the framework is performing as designed, but it took careful thought to figure out what was going on. PHP7.3
To Top