Search code examples
phpclassdelegation

PHP use __get to call a method?


I've got some PHP cruft that I would like to delegate methods. Sort of a poor-man's mixin.

Basically I would like the following:

<?php

class Apprentice
{
    public function magic() {
        echo 'Abracadabra!';
    }
}

class Sourcerer // I work magic with the source
{
    private $apprentice;

    public function __construct(){
        $this->apprentice = new Apprentice();
    }

    public function __get($key) {
        if (method_exists($this->apprentice, $key)) {
            return $this->apprentice->{$key};
        }
        throw Exception("no magic left");
    }
}

$source = new Sourcerer();
$source->magic();
?>

To not throw a Fatal error: Call to undefined method Sourcerer::magic() in .../test__get.php.


Solution

  • public function __call($name, $args) {
        if (method_exists($this->apprentice, $name)) {
            return $this->apprentice->$name($args);
        }
        throw Exception("no magic left");
    }
    

    ps: use __call for methods as __get is only for properties. And yes, it is better to use call_user_func_array, otherwise arguments are supplied as array to the magic function.

    return call_user_func_array(array($this->apprentice, $name), $args);