4

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ć
  • 9,107
  • 2
  • 30
  • 43
Einius
  • 1,352
  • 2
  • 20
  • 45

2 Answers2

14

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
  • 12,375
  • 12
  • 51
  • 73
7

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ć
  • 9,107
  • 2
  • 30
  • 43