如何检查对象在 Symfony2 中是否有方法 [英] How to check if object has method in Symfony2

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

问题描述

我想使用同一段代码来管理多个实体,但它可能会有所不同,具体取决于它是否有某种方法.这就是为什么我需要按名称检查对象是否具有方法.有没有办法做到这一点?

I want to use the same piece of code for managing multiple entities but it might be a little different depending if it has some method or not. Thats why I need to check if object has method by name. Is there any way to do that?

推荐答案

你可以简单地使用is_callable:

if (is_callable([$entity, 'methodName']))
    doSomething();

更简洁的方法是使用 instanceof 检查对象的类.因为方法会来来去去,但是一个对象的特性是由它的类决定的:

A cleaner approach is to check for the class of an object with instanceof. Because methods will come and go, but the character of an object is determined by its class:

if ($entity instanceof \Some\Bundle\Entity\Class)
    doSomething();

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

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