php的魔术方法 __call

2019-05-08  本文已影响0人  个00个

官方文档

https://www.php.net/manual/en/language.oop5.overloading.php#object.call

官方示例

<?php
class MethodTest
{
    public function __call($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

这时候如果本身有这种方法

<?php
class MethodTest
{
    public function __call($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling object method '$name' "
             . implode(', ', $arguments). "\n";
    }

    /**  As of PHP 5.3.0  */
    public static function __callStatic($name, $arguments)
    {
        // Note: value of $name is case sensitive.
        echo "Calling static method '$name' "
             . implode(', ', $arguments). "\n";
    }

    public function runTest() {
        echo "office runTest";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

// MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

则不会执行 __call

结论:
__call 作为魔术方法当某个类执行了没有实现的方法时, 会去执行 __call .

上一篇 下一篇

猜你喜欢

热点阅读