美文网首页
php的魔术方法 __call

php的魔术方法 __call

作者: 个00个 | 来源:发表于2019-05-08 13:50 被阅读0次

官方文档

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 .

相关文章

网友评论

      本文标题:php的魔术方法 __call

      本文链接:https://www.haomeiwen.com/subject/kqhmoqtx.html