如何检查对象方法是否存在? [英] How can I check if an object method exists?

查看:68
本文介绍了如何检查对象方法是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当方法getProductgroup存在时,我才想使用一些代码. 我的第一种方法:

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

我收到错误消息:

编译错误:不能在表达式的结果上使用isset() 可以使用"null!==表达式"代替)

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:

试图调用名为class的未定义方法"getProductgroup" "App \ Entity \ Documents".

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

推荐答案

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

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

在您的代码中尝试

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

这篇关于如何检查对象方法是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆