Function to check on variables that may or may not exist - PHP
I have a function that is meant to check if two variables match, but with different values. It's a kinda complicated idea... but here's an example of its usage:
match($set1->test,"YES",$set2->test,"ON")
It will return true if$set1->test == "YES" && $set2->test == "ON"
Here's an example of how its implemented:
function match($field1,$val1,$field2,$val2) {
if ((isset($field1) && $field1 == $val1) && (isset($field2) && $field2 == $val2))
{
return true;
}
return false;
}
So the big issue here is you CANNOT doisset
inside a function with the function's arguments. It's pointless, because the error gets thrown that$set1->test
does not exist when the function is called, and if it isn't an object property then the variable gets initialized in the function scope anyway. It seems that the only way to get around this is to do the isset test on$set1->test
and$set2->test
before passing them to the function, but I really don't want to. It feels unnecessary.
My question is how can I callmatch($set1->test,"YES",$set2->test,"ON")
when$set1->test
or$set2->test
has not been set?
ANSWER
I'm going to use a variation on Tamás's answer. I will have a separate function calledprop
, like this:
function prop($obj, $property) {
if (property_exists($obj,$property)) {
return $obj->$property;
}
return null;
}
Then I'll callmatch
like this:
match(prop($set1,'test'),"YES",prop($set2,'test'),"ON")
Thanks!
Answer
Solution:
Try using property_exists
Answer
Solution:
It's not very popular, but this could be a valid use for the
@
modifier to disable errors:Answer
Solution:
I would do something like this: