3

I have a function like this (using PHP 7.1):

function myfunction(&$first = null, $second = null)
{   // do something
}

What I want to achieve is to pass null as the first parameter and pass something as the second parameter:

myfunction(null, $something);

When I do that I get the "Only variables can be passed by reference" error.

But of course, null is the default of the first parameter, so the function was designed to handle null as the first parameter.

Is there a way to do it?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Roland Seuhs
  • 1,878
  • 4
  • 27
  • 51
  • Possible duplicate of [PHP by-reference parameters and default null](https://stackoverflow.com/questions/280385/php-by-reference-parameters-and-default-null) – Nigel Ren Apr 05 '18 at 11:34
  • You can call by changing parameter order like myfunction($something); dont pass second and change function to myfunction($second = null, &$first = null){ } //$first take the default value if not passed – Mangesh Sathe Apr 05 '18 at 11:34
  • @NigelRen: The other question is useless because you cannot find it when you search for "Only variables can be passed by reference" – Roland Seuhs Apr 05 '18 at 11:43
  • Why is it useless because you can't use those words to search for it? The purpose of a duplicate is that it's there because it answers the same problem as your having. – Nigel Ren Apr 05 '18 at 12:28
  • I searched both in Google and on Stackoverflow and was not able to find it - plus if you compare the answers, the other one is copy&pasted code with more than half unrelated to the question! – Roland Seuhs Apr 08 '18 at 06:16

2 Answers2

6

Instead of sending null, you can send an undeclared variable, like (DEMO):

<?php
function myfunction(&$first = null, $second = null)
{   // do something
}
myfunction($null, $something);

This will serve the purpose of executing the function and not breaking your code.

PHP 8+:

In PHP 8 we have Named Parameters, so we don't even need to pass the $first param if we don't want to (DEMO):

<?php
function myfunction(&$first = null, $second = null)
{   // do something
}
myfunction(second: $something);
Dharman
  • 30,962
  • 25
  • 85
  • 135
mega6382
  • 9,211
  • 17
  • 48
  • 69
0

Not possible. A reference cannot be empty as first parameter if the function has more than 1 parameter.

Here are some possibilities:

function func($a = null, &$b = null) {}
function funcb(&$a, $b = null) {}

calling:

$a = null;
func($a, $b)
funcb($a)
sridesmet
  • 875
  • 9
  • 19