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;

  1. <?php
  2. // This example assumes ayou already have a DB connection
  3. // established and a database has been selected
  4.  
  5. class Database {
  6.    
  7.     public function __call($method){
  8.        
  9.         $sql = "SELECT * FROM " . $method;
  10.         $r = mysql_query($sql);
  11.         return mysql_fetch_assoc($r);
  12.        
  13.     }
  14.    
  15. }
  16.  
  17. $x = new Database();
  18.  
  19. $rows = $x->table();
  20.  
  21. print_r($rows);
  22.  

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!

Leave a Reply