PHP catching all function calls

By | June 15, 2009

Recently I came accross something really fancy that was introduced in PHP 5. It is appearantly possible for any class to catch all functions that are called on a class. So one function would catch $obj->callOne() as well as $obj->callTwo().

So why is this a nice feature to have, well because I am a very lazy progammer and this feature allows me to magically generate getters and setters. To do this I have the following setting for each class:

  1. The constructor method __construct initializes an array containing the names of all variables that we want to store. We also create a second array to save the values in for the variables.
  2. We implement the __call function to catch all functions being called on the object, which is currently still undocumented by PHP.net

So a basic class would look something similar to this:

class MyObject {
    private $my_vars = array();
    private $allowed_vars;

   function __construct() {
       $this->allowed_vars = array('var1', 'var2', 'var3');
    }

   function  __calls($function_name, $arguments) {
       $_variablename = substr($function_name, 3);
       if (array_search($_variablename, $this->allowed_vars) !== FALSE) {
          if (stripos($function_name, 'get') == 0 && stripos($function_name, 'get') !== FALSE) {
             return $this->my_vars[$_variablename];
          } else if (stripos($function_name, 'set') == 0 && stripos($function_name, 'set') !== FALSE) {
             $this->my_vars[$_variablename] = $arguments[0];
          }
       }
       else throw new Exception('Unkown function called on '. __CLASS__);
   }
 }

Which does exactly that which I described above. Mind you it’s just a very basic example but it shows the power of a catch all function.

One thought on “PHP catching all function calls

  1. Sigrid Boggan

    This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a high quality resource for free. It is like the phrasewhat goes around comes around routine.

    Reply

Leave a Reply