我有一些我想委託方法的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