首页 > 解决方案 > call_user_func_array 不执行 __callStatic 魔术方法

问题描述

我有这两个类:

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();从控制器调用时,它__callStaticService类中执行,但是当Service类尝试getItems()从 CacheService 调用时,它不在类__callStatic中执行CacheService。究竟是什么问题?

标签: phpmagic-methods

解决方案


__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

推荐阅读