Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass default value instead of reference

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?

like image 967
Roland Seuhs Avatar asked Jul 28 '26 15:07

Roland Seuhs


1 Answers

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);
like image 137
mega6382 Avatar answered Jul 30 '26 04:07

mega6382



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!