Aug '13

PHP’s Catch Functions

PHP has three key catch (or ‘method missing’) functions, used when calls are made to class methods or parameters that don’t exist. These can be incredibly useful and time-saving if used properly, and cause incredible headaches if used badly!


This catches calls to any method names that don’t exist in the current class, or any (non-private) methods any parent classes. The called method name will be passed as the first argument and any arguments will be wrapped in an array and passed as the second argument. I have found this to be particularly useful to save myself the creation of getter and setter methods on my classes – a quick match against the first three letters can tell me if it’s a get or a set that has been called and I can then perform the operation on whatever structure actually holds the data I’m after.

__get() and __set()

These are used as overrides for calls to get and set class variables directly e.g. $class->variable
I find them particularly useful to provide shortcuts to getter and setter methods so the methods can be used as ‘virtual’ class variables e.g.

public function __get($key) {
    $method_name = 'get' . ucfirst($key);
    return (method_exists($this, $method_name)) ? $this->$method_name() : false);
public function __set($key, $value) {
    $method_name = 'set' . ucfirst($key);
    return (method_exists($this, $method_name)) ? $this->$method_name($value) : false);

Leave a Reply