0

Guys I just came across the __call() PHP function. I tried to understand what this is used through the manual here http://php.net/manual/en/language.oop5.overloading.php#object.call But all that is mentioned here is that

__call() is triggered when invoking inaccessible methods in an object context.

which is not really clear honestly. I tried looking for other examples online, but they all seem complicated. Can anyone explain using a simple example what is __call() and what is it good for?

1
  • __call is executed when you try to invoke non-existent method in class. PHP page you provided has an example. Commented Jul 12, 2018 at 16:07

1 Answer 1

6

Consider this:

class Foo
{
    public function __call($name, $args)
    {
        echo "you tried to call method $name with these args:";
        print_r($args);
    }
}

$foo = new Foo();
$foo->bar($args);

Note there is no method named bar. Normally, calling it will produce an error. However, in this case, you've defined a __call() method. So, instead of generating an error, PHP will invoke this method, passing it the name of the method you tried to call, and the arguments you tried to call it with.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. This helps!: )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.