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
You can do this using func_get_args like so:
This func goes one step further and would give you the first non empty value of any number of args (you could always force it to only take up to two args but this look more useful to me like this).
EDIT: original version didn't use compact to try and make an array of args and STILL gave an error. Error reporting bumped up a notch and this new version with compact is a little less tidy, but still does the same thing and allows you to provide a default value for non existent vars.
There are valid cases where checking becomes cumbersome and unnessesary.
Therfore i've written this little magic function:
It doesn't require any changes to myHappyFunction().
You'll have to change
to
Stating your intent explicitly. which makes it good practice in my book.
I'm sure there could be a great discussion on ternary operators vrs function calls. But the point of this question was to see if we can create a function that won't throw an error if a non existent value is passed in without using the '@'
Sean, you could do:
EDIT:
And I told you, check it with
isset()
. A ternary conditional's first part doesn't check null or not null, it checkstrue
orfalse
. If you try to checktrue
orfalse
on a null value in PHP, you get these warnings.isset()
checks whether a variable or expression returns a null value or not, and it returns a boolean, which can be evaluated by the first part of your ternary without any errors.this returns either $value OR $default. Depending upon the value of $value. If it is 0, false, empty or anything similar the value in $default will be returned.
I'm more going for the challenge to emulate functions like empty() and isset()
You don't get any error when a variable is passed by reference (PHP will create a new variable silently):
But I recommend against abusing this for hiding programming errors.