通常,当您与第 3 方 API 通信或方法/成员结构不清楚时,这些方法很有用。
假设您正在编写一个通用的 XML-RPC 包装器。由于在下载 WDL 文件之前您不知道可用的方法,因此使用重载是有意义的。
然后,不要编写以下内容:
$xmlrpc->call_method('DoSomething', array($arg1, $arg2));
Run Code Online (Sandbox Code Playgroud)
您可以使用:
$xmlrpc->DoSomething($arg1, $arg2);
Run Code Online (Sandbox Code Playgroud)
这是更自然的语法。
您还可以按照与变量对象的方法重载相同的方式使用成员重载。
您需要注意的一件事是:仅将其使用限制为可变结构对象,或者仅将其用于 getter 和 setter 的语法快捷方式。在类中保留 getter 和 setter 来分隔多个方法中的业务逻辑是有意义的,但将其用作快捷方式也没有什么问题:
class ShortcutDemo {
function &__get($name) {
// Usually you want to make sure the method
// exists using method_exists, but for sake
// of simplicity of this demo, I will omit
// that logic.
return call_user_method('get'.$name, $this);
}
function __set($name, &$value) {
return call_user_method('set'.$name, $this, $value);
}
private $_Name;
function &getName() { return $this->_Name; }
function setName(&$value) { $this->_Name = $value; }
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以继续使用 getter 和 setter 来验证和设置数据,并且仍然使用语法快捷方式:
$shortcut->Name = 'Hello';
Run Code Online (Sandbox Code Playgroud)