【问题标题】:How can I check if an object method exists? [duplicate]如何检查对象方法是否存在? [复制]
【发布时间】:2019-09-09 12:42:47
【问题描述】:

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

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 !== 表达式”代替)

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

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

试图调用类的名为“getProductgroup”的未定义方法 “应用\实体\文档”。

【问题讨论】:

  • 你不会相信但method_exists()

标签: php oop object methods isset


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我能问个问题吗?我在某些情况下存在getProductgroup(),但不存在getProductgroup()->getUuid()。所以我更需要检查getProductgroup()->getUuid()是否存在
  • @marila 是的,您也需要申请相同的支票
  • 我这样做了if(method_exists($item, 'getUuid')){,但仍然收到错误消息Attempted to call an undefined method named "getUuid" of class "Doctrine\ORM\PersistentCollection".
  • @marila 答案已更新。
  • 啊谢谢,我只是不明白怎么做! :)
猜你喜欢
  • 2018-12-23
  • 1970-01-01
  • 2012-02-25
  • 1970-01-01
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 2015-05-26
相关资源
最近更新 更多