3

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?

Igor Pantović
  • 8,864
  • 2
  • 29
  • 43
Einius
  • 1,302
  • 2
  • 20
  • 44

2 Answers2

13

You can simply use is_callable:

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

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();
lxg
  • 11,188
  • 11
  • 43
  • 67
5

This has nothing to do with Symfony, it's basic PHP thing: use method_exists PHP function.

bool method_exists ( mixed $object , string $method_name )

PHP Docs

While this is a perfectly fine way to go around it, you might want to look into interfaces as an alternative: PHP Interfaces

If you do decide to use them, you can just check if object is an instance of your interface:

interface MyAwesomeInterface
{
    public function myFunction();
}


if ($myObject instanceof MyAwesomeInterface) {
    $myObject->myFunction();
}
Igor Pantović
  • 8,864
  • 2
  • 29
  • 43