Search code examples
phpoopobjectmethodsisset

How can I check if an object method exists?


I want to use some code only if the method getProductgroup exists. My first approach:

if(isset($item->getProductgroup())){
 $productgroupValidation = 0;
 $productgroupId = $item->getProductgroup()->getUuid();
 foreach($dataField->getProductgroup() as $productgroup){
   $fieldProductgroup = $productgroup->getUuid();
   if($productgroupId==$fieldProductgroup){
       $productgroupValidation = 1;
  }
}

I got the error message:

Compile Error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

if(($item->getProductgroup())!==NULL){
     $productgroupValidation = 0;
     $productgroupId = $item->getProductgroup()->getUuid();
     foreach($dataField->getProductgroup() as $productgroup){
       $fieldProductgroup = $productgroup->getUuid();
       if($productgroupId==$fieldProductgroup){
           $productgroupValidation = 1;
      }
    }

But like this I also get an error message:

Attempted to call an undefined method named "getProductgroup" of class "App\Entity\Documents".


Solution

  • You can use the function method_exists to check if the method is existing in a class or not. for example

    if(method_exists('CLASS_NAME', 'METHOD_NAME') ) 
       echo "it does exist!"; 
    else 
       echo "nope, it is not there...";
    

    In your code try

    if(method_exists($item, 'getProductgroup')){
    $productgroupValidation = 0;
    if(method_exists($item->getProductgroup(), 'getUuid'))
    {
       $productgroupId = $item->getProductgroup()->getUuid();
       foreach($dataField->getProductgroup() as $productgroup)
       {
            $fieldProductgroup = $productgroup->getUuid();
            if($productgroupId==$fieldProductgroup){
                $productgroupValidation = 1;
            }
        }
     }
    }