Home > Software design >  Is there a way to pass temporary arrays by reference in php?
Is there a way to pass temporary arrays by reference in php?

Time:10-29

Consider a simple function:

function pass(&$arr)
{
  // do something
}

If I call it like this…

$a = [1,2,3];
pass($a);

…this will work. However, if I do it like this,…

pass([1,2,3]);

…it will fail with the error Cannot pass parameter 1 by reference.

Why cant I get a reference to the temporary array in a function scope where the array is valid?

CodePudding user response:

Well you can't do that ... as per php manual : Only variables should be passed by reference.

Though you can create a function that creates a variable in it's scope and then returns the reference (But again whats the point of passing it by reference when you are passing array directly ? I don't find any use of it or am I missing something ?)

function pass(&$arr)
{
  // do something
}


function &scopeVar($arr){
    return $arr;
}

pass(scopeVar([1, 2, 3]));

CodePudding user response:

@rhaven;

I have no clue what you are attempting to do here, but the error message is not only correct, it is meaningful. The array is created on-the-fly, and while it actually exists in memory, there are no references to it except the temporary one passed into the function.

Attempting to make a reference to an ephemeral value like this is an oxymoron. It simply makes zero sense.

@anees supplied an interesting workaround, but the bottom line is I believe you need to rethink the code, and why you either need:

  1. a temp variable in the call, or
  2. a reference in the function.

CodePudding user response:

The [1,2,3] in the function call isn't a variable, it's just a hard coded value. You can pass that to a function that's pass by value, but not pass by reference. If the function is pass by reference it needs a variable. What's more, in PHP 7 they added a notice in strict standards if you try to declare the variable in the method call, i.e. pass(($a = [1,2,3]));: https://www.php.net/manual/en/migration70.incompatible.php

This page doesn't give a reason for the decision.

  • Related