call_user_func_array不执行__callStatic魔术方法

时间:2018-08-24 12:45:58

标签: php magic-methods

我有这两节课:

class Service {
    public static function __callStatic($name, $arguments)
    {
        // ... opt-out code
        $result = call_user_func_array([CacheService::class, $name], $arguments);
        // ... opt-out code
    }
}

还有这个

class CacheService
{
    public static function __callStatic($name, $arguments)
    {
        // ... opt-out code
        if (self::getCacheInstance()->has('some_cache_key')) {
            return call_user_func_array(['self', $name], $arguments);
        }
        // ... opt-out code
    }

    public static function getItems()
    {
        //... do operations
    }
}

当我从控制器调用Service::getItems();时,它将在__callStatic类中执行Service,但是当Service类试图从CacheService调用getItems()时,它将执行不执行__callStatic类中的CacheService。 到底是什么问题?

1 个答案:

答案 0 :(得分:2)

__callStatic仅在没有带有调用方法名称的静态方法时执行

您的Service类不包含getItems()方法,因此__callStatic被执行。

您的CacheService确实包含了它,因此getItems被执行了

http://php.net/manual/en/language.oop5.overloading.php#object.callstatic

示例:

<?php

class A {
    public static function __callStatic() {
        echo "A::__callStatic";
    }
}

class B {
    public static function __callStatic() {
        echo "B::__callStatic";
    }

    public static function getItems() {
        echo "B::getItems";
    }
}

A::getItems(); // A::__callStatic
B::getItems(); // B::getItems()
B::anotherFunction(); // B::__callStatic
相关问题