php - 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();
从控制器调用时,它__callStatic
在Service
类中执行,但是当Service
类尝试getItems()
从 CacheService 调用时,它不在类__callStatic
中执行CacheService
。究竟是什么问题?
解决方案
__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
推荐阅读
- php - Index.php 在一个请求中调用了两次
- javascript - 使用解构不是在 forEach 循环中分配。如果我写 object.property,它正在分配
- r - R中的状态集群颜色
- r - R中闪亮的应用程序创建和输出的问题
- jmx - Prometheus jmx 导出器模式匹配属性和项目
- python - 巴特沃斯过滤器python
- sql - 使用 LOP_FORMAT_PAGE 条目向 SQL Server 日志文件 (.ldf) 发送垃圾邮件
- c# - 如何避免图像 MS Bot 构建器框架的自动重新声明
- sql - How to use a Database Variable Name in dynamic SQL with visual studio for a SQL Server Project?
- python - 在 c++ qt 应用程序的后台运行程序