如何检查对象方法是否存在?

How can I check if an object method exists?

我只想在 getProductgroup 方法存在的情况下使用一些代码。 我的第一种方法:

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

我收到错误消息:

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

但是像这样我也收到一条错误信息:

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

您可以使用函数 method_exists 来检查方法是否存在于 class 中。例如

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

在你的代码中尝试

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