How can I check if an object method exists? [duplicate]

佐手、 提交于 2020-01-22 03:39:11

问题


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".


回答1:


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;
        }
    }
 }
}


来源:https://stackoverflow.com/questions/55758541/how-can-i-check-if-an-object-method-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!