ButterMyBitter
ButterMyBitter

Reputation: 93

Return string if method called inside of a class doesn't exist

Upon searching for hours, I've stumbled upon method exists, function exists, magic methods and many other manuals, forum posts and blogs but they are either not clear enough for me or aren't what I'm looking for. In this stack overflow question and as well as this one, they are almost what I am looking for, only they check method_exists against a static method name.

Here's my issue:
I want a method inside of my class to check to see if FunctionName exists inside of the class MyClassName when called by $foo = new MyClassName(); $foo->FunctionName(); and, if it does not exist, to echo "Test!". In other words, if the method being called doesn't exist in MyClassName, echo "Test!".

I know I can check it with objects like $foo = new MyClassName(); and such, but I am looking for a method/function inside of my class that can do it.

Many thanks!

Upvotes: 1

Views: 130

Answers (2)

Lyes BEN
Lyes BEN

Reputation: 1010

What you are looking for is the magic method __call() and the function method_exists().

Do as follows :

 public function __call($name, $arguments) {
      if(!method_exists($this, $name)) {
        echo "Method does not exist [called method '$name' with parameters". implode(', ', $arguments). "]\n";
      }
  }

Upvotes: 0

Jake
Jake

Reputation: 822

Your search took you exactly where you needed to go.

If you implement a __call method in the class definition (see the magic methods link you provided), it will be used when the method is inaccessible (doesn't exist or is private or protected, depending on whether you're calling the method from a child class or not, respectively).

Upvotes: 2

Related Questions