Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php function argument error suppression, empty() isset() emulation

I'm pretty sure the answer to this question is no, but in case there's some PHP guru

is it possible to write a function in a way where invalid arguments or non existent variables can be passed in and php will not error without the use of '@'

Much like empty and isset do. You can pass in a variable you just made up and it won't error.

ex:

empty($someBogusVar); // no error

myHappyFunction($someBogusVar); // Php warning / notice
like image 419
SeanDowney Avatar asked Sep 10 '08 19:09

SeanDowney


2 Answers

Summing up, the proper answer is no, you shouldn't (see caveat below).

There are workarounds already mentioned by many people in this thread, like using reference variables or isset() or empty() in conditions and suppressing notices in PHP configuration. That in addition to the obvious workaround, using @, which you don't want.

Summarizing an interesting comment discussion with Gerry: Passing the variable by reference is indeed valid if you check for the value of the variable inside the function and handle undefined or null cases properly. Just don't use reference passing as a way of shutting PHP up (this is where my original shouldn't points to).

like image 124
Vinko Vrsalovic Avatar answered Nov 15 '22 21:11

Vinko Vrsalovic


You don't get any error when a variable is passed by reference (PHP will create a new variable silently):

 function myHappyFunction(&$var)
 {       
 }

But I recommend against abusing this for hiding programming errors.

like image 33
Kornel Avatar answered Nov 15 '22 19:11

Kornel