Function to check on variables that may or may not exist - PHP

482

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!

194

Answer

Solution:

Try using property_exists

function match($obj1, $obj2,$property,$val1,$val2) {
    if ((property_exists($obj1, $property) && $obj1->$property == $val1) && (property_exists($obj2, $property) && $obj2->$property == $val2)) 
    {
       return true;
    }
    return false;
}
597

Answer

Solution:

It's not very popular, but this could be a valid use for the@ modifier to disable errors:

@match($set1->test, "YES", $set2->test, "ON");
984

Answer

Solution:

I would do something like this:

function match($field1=NULL,$val1=NULL,$field2=NULL,$val2=NULL) {
    $result = false;
    if (!is_null($field) && !is_null($val1) && !is_null($field2) && !is_null($val2)) {
            if ($field1 == $val1 && $field2 == $val2) {
                $result = true;
            }
            else {
                $result = false;    
            }  
    } 
    return $result;
}

People are also looking for solutions to the problem: css - Dynamically update and compile SCSS with PHP on database update

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.