PHP 面向对象基础:__call() 方法的应用 2 个改进

在对象中调用一个不可访问的方法时,__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');
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!