24
aug
2008

PHP __call and __callStatic Magic methods

This is just a quick post to show the use of the magic methods call and callStatic. It’s following on in my Magic Method series. The concept is very similar to set/get, basically PHP attempts to call a method on a class, if it doesn’t exist the call method is invoked (if it does exist). callStatic is exactly the same but with static method calls.

Note that __callStatic will only be available from PHP 5.3 onwards.

Here is a quick example to show it in use;

table();

print_r($rows);

In this example, basically the class is set up to return all the rows from a table, to do this you call a method with the name of the table.

It’s quite a simple example but I think it opens up some interesting possibilities.

I find that get and set are not that useful if you know what methods/properties a class is going to have. However, if you don’t know it can be very handy. If you’ve ever used the PHP SoapClient class then you will have already used call. The SoapClient class doesn’t know what methods are going to be in the WSDL until run time, therefore it is determined programmatically by the call method. This allows for each access to web services. If you have not tried SoapClient and don’t have a clue what I’m talking about... You should try it, it’s great.

Oh yeah, the sample code above gives you a small clue about a side project I’ve been working on. It started off as a simple idea but its proving to be pretty cool ;) I hope to write about it soon and release some examples but I really need __callStatic to make using it must easier!

Short url - Related tags: magic-methods, php

blog comments powered by Disqus