__call catches static method calls

五迷三道 提交于 2020-01-03 19:39:53

问题


I'm using both the magic methods _call and _callStatic for my own implementation of something like an ORM/Activerow. They're mainly meant for catching certain function calls: __call is responsible for getters and setters, and __callStatic for findBy methods (e.g. findById).

To map foreign keys, i'm trying to convert calls to e.g. getArticle to return the value of Article::findById(). To do that, i'm using this case inside my __call:

if (strstr($property, "_id")) {  
 return $foreignClass::findById($this->getId()); 
}

where $property is the substring after set or get in __call, and $foreignClass the rest of the string. So, in the case of the call getArticle, $property would be get and $foreignClass would be Article.

I've placed some echoes to ensure that the values are correct. However, my __call method gets called instead of my __callStatic. If i make an implicit static method findById, it does get called (so it does recognize it as a static call). If i specifically call Article::findById(), __call also catches it.

Is this an error with the relatively new __callStatic, or am i doing something wrong?

EDIT: The problem seems to reside in this part:

_call() is triggered when invoking inaccessible methods in an object context.
__callStatic() is triggered when invoking inaccessible methods in a static context.

Though i am calling it on a class, i am calling it from an object context. Is there a way to get into the static context in this case?


回答1:


Since the code you give runs in the context of an Activity object and since the value of $foreignClas is Article, which is an ancestor of Activity, PHP assumes that you are intending to call an ancestor's implementation of the method.

To break out of the object context there is AFAIK no option other than this absolutely hideous technique:

$id = $this->getById();
return call_user_func(
    function() use($foreignClass, $id) { 
        return call_user_func("$foreignClass::findById", $id);
    }
);



回答2:


The __callStatic magic method was only introduced in PHP 5.3. Prior to that, I believe static calls were routed through __call just like normal method calls. My guess would be that you are using a PHP version that is < 5.3. What is the output of php -v on the command line?



来源:https://stackoverflow.com/questions/13232445/call-catches-static-method-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!