PHP 面向对象基础:__call() 方法的应用
在对象中调用一个不可访问的方法时,__call()
会被调用。__call()
被用于方法重载,它是 PHP 魔术方法 中的一种。
__call ( string $name , array $arguments )
$name
参数是要调用的方法名称。 $arguments
参数是一个枚举数组,包含着要传递给方法 $name
的参数。
调用受限方法
如果一个类没有设置 __call()
,对象无法调用受限方法。
class Person
{
protected function run($arg)
{}
}
当对象调用受限方法时,会出现以下错误信息。
$person = new Person();
// atal error: Uncaught Error: Call to protected method Person::run()
$person->run('David');
设置魔术方法 __call()
。
class Person
{
private function run($args)
{
foreach ($args as $arg) {
echo 'Do you like running, ' . $arg . '?<br />';
}
}
public function __call($name, $arguments)
{
// 如果类中有这个方法,就调用
if ($name === 'run') {
$this->run($arguments);
} else {
echo 'Calling unavailable function ' . $name . '().<br />';
}
}
}
对象成功调用受限方法。
$person = new Person();
// Do you like running, David?
// Do you like running, Lily?
$person->run('David', 'Lily');
调用不存在的方法
调用不存在的方法时,给出调用无效方法的信息提示。
//Calling unavailable function jump().
$person->jump('David', 'Lily');