PHP使用__get来调用方法?

quo*_*tor 1 php class delegation

我有一些PHP cruft我想委托方法.一个穷人的混合物.

基本上我想要以下内容:

<?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();
?>
Run Code Online (Sandbox Code Playgroud)

不扔一个Fatal error: Call to undefined method Sourcerer::magic() in .../test__get.php.

Che*_*ery 9

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

PS:使用__call的方法是__get仅适用于性能.是的,最好使用call_user_func_array,否则参数作为数组提供给magic函数.

return call_user_func_array(array($this->apprentice, $name), $args);
Run Code Online (Sandbox Code Playgroud)