Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Make reference parameter optional?

Tags:

php

Say I've defined a function in PHP, and the last parameter is passed by reference. Is there any way I can make that optional? How can I tell if it's set?

I've never worked with pass-by-reference in PHP, so there may be a goofy mistake below, but here's an example:

$foo; function bar($var1,&$reference) {     if(isset($reference)) do_stuff();     else return FALSE; }  bar("variable");//reference is not set bar("variable",$foo);//reference is set 
like image 633
Jake Avatar asked May 19 '13 16:05

Jake


2 Answers

Taken from PHP official manual:

NULL can be used as default value, but it can not be passed from outside

<?php  function foo(&$a = NULL) {     if ($a === NULL) {         echo "NULL\n";     } else {         echo "$a\n";     } }  foo(); // "NULL"  foo($uninitialized_var); // "NULL"  $var = "hello world"; foo($var); // "hello world"  foo(5); // Produces an error  foo(NULL); // Produces an error  ?> 
like image 87
Martin Perry Avatar answered Sep 28 '22 16:09

Martin Perry


You can make argument optional by giving them a default value:

function bar($var1, &$reference = null) {     if($reference !== null) do_stuff();     else return FALSE; } 

However please note that passing by reference is bad practice in general. If suddenly my value of $foo is changed I have to find out why that is only to find out that it is passed by reference. So please only use that when you have a valid use case (and trust me most aren't).

Also note that if $reference is supposed to be an object, you probably don't have to (and shouldn't) pass it by reference.

Also currently your function is returning different types of values. When The reference is passed it returns null and otherwise false.

like image 40
PeeHaa Avatar answered Sep 28 '22 17:09

PeeHaa