Reputation: 1995
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?
Upvotes: 3
Views: 257
Reputation: 9396
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.
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);
Upvotes: 7
Reputation: 895
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)
Upvotes: 0