This question have a similar question here and here, too. I could have posted this as a comment but I don’t have the privilege yet so I posted this. I have also found similar question with no answer that satisfy my requirements. I will do the codes do the further talking.
I c/c++ you can do like this:
void CallMe(int *p = NULL)
{
if ( p!= NULL )
*p = 0;
}
CallMe(); // Calling the function without arguments the function will do nothing. But...
int n;
CallMe(&n);
// Here, you are passing a pointer to your n that will be filled by the CallMe function.
For c/c++ programmer, you know what to expect on those two calls.
Now, I want to do it in PHP. And when I do my searching, the following are most popular methods that are suggested in the search result: isset
, is_null
and empty
. I did my trial-and-error but nothing works like that c/c++ sample.
function CallMe(&$p=null)
{
if ($p==null)
return;
if(!isset($p))
return;
if (is_null($p))
return;
if (empty($p))
return;
$p = time();
return 'Argument was set to ' . $p;
}
CallMe();
On the first call where no argument is supplied, all argument evaluations will result to true and the function will do nothing. Let’s try with an argument.
$a = 1;
CallMe($a);
Of source, the function will now make some sense out of that $a variable. But…
$a = null;
CallMe($a);
In this last call, the function will behave as if no argument is given.
Now, what I want to achieve is the function to be able to check (like the c/c++ sample) if an argument was supplied. Or, is there a way we could pass a pointer to a variable in PHP?
2
Answers
There is an old function you may call to check the number of function arguments that is actually supplied by user: func_num_args()
Output:
The main difference is C / C++ has a distinct pointer type, while PHP does not. From a function perspective, there is no way to distinguish if
$p
is:NULL
; or$a
) with aNULL
valueThere used to be run time pass-by-reference in PHP, but it was removed back in PHP 5. Which means the lack of reference / pointer type is probably a design choice of the language. And it’s unlikely to change in the foreseeable future.
If you have multiple optional value, the closest thing I can think of is to use a value holder object instead of raw variable.
In PHP, object instances are ALWAYS passed by reference. Hence there is no need to explicitly add a
&
to it.Output:
This is not exactly what you asked for, but this is the closest I can think of.