PHP: __call Magic

July 10, 2009

Lastnight as I was researching how to build a plugin system for a cms I am working on I ran across several implementations using the __call method. I had not used it before myself, but after doing a little googling I devised a test. It really is quite simple and can be a powerhouse in your applications.

First, what is this __call thing even for? Remember those classes you built? Then remember how you were doing something else and forgot you had not yet created a method in the class to handle it and your application blew up? That is where __call comes to the rescue! Whenever a method in your class is called that does not exist PHP automagically sends the request to the __call() method. If __call exists then PHP assumes it knows how to take care of the missing method. If it does not exist is when things get hairy, fatal errors get thrown, the application blows up, and you loose your job cause one of the company execs got a phone call while in Hawaii. Oops, consider using __call in any of your important objects 😀

Let’s start with an example of the calling code:

$Car = new Car();
$Car->Fly('Super Jets');

I am using a Car for this example. Most cars can go pretty fast, but currently there are no cars that can fly. Normally calling Fly() would cause a fatal error right? Not this time.

Take a look at the Car class:

class Car {

        // Constructor
        public function __construct() {
                echo "Your car has arrived";

        // Let's roll! How fast?
        public function ZoomZoom($Speed) {
                echo "And we're off at an amazing $Speed! Hope you're buckled!";

         * This is a magic function.
         * This function gets called when a method that does
         * not exist in this class is called. Once inside this
         * method you are free to deal with it however you
         * would like
        public function __call($Function, $Args) {
                $Args = implode(', ', $Args);
                echo "I can't $Function you idiot! Especially with $Args! Hoser";

Note the two arguments. They do not have to be called that, but it will help you remember what they are in 6 months.

Here is the output:

Your car has arrived
And we're off at an amazing 120! Hope you're buckled!
I can't Fly you idiot! Especially with Super Jets! Hoser

Pretty simple eh? I hope you realize the potentially huge impact the use of this magic method could have on your application. Heck, if nothing else use it with a logger to log errors.