ibrow

ibrow blog

archive for July, 2007

Fake Method Overloading

Wednesday, July 4th, 2007 by Rob

Been struggling for the past hour or so with method overloading within objects, so I thought I’d write a little not on my blog to hopefully help others and to remind myself.

The premise for this is that I was writing a new database wrapper class to speed up the rather rubbish database module I have been using previously. My plan was to encapsulate all my methods in the wrapper (such as get_table_name() etc) in my class then all others fire off to the ADODB class by PHPlens. My plan was to do this with method overloading, such as:

public function __call($m, $a) {
    return $this->db->$m($a);   
    throw new Exception(’Tried to call unknown method ‘.get_class($this->db).’::’.$m);
}

However, PHP5 doesn’t seem to support that, which is irritating. After some search on the web I find out that PHP5 doesn’t support real overloading.

So after much effort and searching the web and docs I decide to use the call_user_func_array(&obj) technique.

Finished method below:

public function __call($m, $a) {
    // check the method being called exists
    if (method_exists($this->db, $m)) {
        return call_user_func_array(array(&$this->db, $m), $a);
    }
    else {
        throw new Exception(’Tried to call unknown method ‘.get_class($this->db).’::’.$m);
    }
}

Seems to work, so please feel free to use

ibrow.com


tel: 020 7183 2328

BarCamp Berlin 3