我有一些我想委托方法的PHP cruft。排序一个穷人的混合。PHP使用__get来调用方法?
基本上我想以下几点:
<?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();
?>
为了不丢一Fatal error: Call to undefined method Sourcerer::magic() in .../test__get.php
。
This ++。 __call是你真正想要的东西。此外,如果您将来希望在静态函数中使用这种功能,您可能需要调查__callStatic。 – Navarr 2012-02-07 01:35:28
Ohhh ...我完全误解了文档,我认为'__call()'是为了调用一个实例,就好像它是一个函数,它是为了实现'$ s = new S(); $ S();'。谢谢! – quodlibetor 2012-02-07 03:38:49
@quodlibetor方法['__invoke'](http://php.net/manual/en/language.oop5.magic.php#object.invoke)用于调用实例,就像它是一个函数一样。 – Wilt 2016-06-11 07:40:32