从PHP的类外部调用受保护的方法 [英] Call a protected method from outside a class in PHP
问题描述
我有一个非常特殊的情况,我需要从类外部调用受保护的方法。我非常清楚我是如何进行编程的,但是在这种特殊情况下,我不会完全反对这样做。在所有其他情况下,我需要继续禁止访问内部方法,因此我想保护该方法。
I have a very special case in which I need to call a protected method from outside a class. I am very conscious about what I do programmingwise, but I would not be entirely opposed to doing so in this one special case I have. In all other cases, I need to continue disallowing access to the internal method, and so I would like to keep the method protected.
有什么优雅的方法可以访问内部方法?类之外的受保护方法?到目前为止,我已经找到此。
What are some elegant ways to access a protected method outside of a class? So far, I've found this.
我想可能会创建目标类的某种双代理实例,从而偷偷提供对内部对象的访问权限...
I suppose it may be possible create some kind of double-agent instance of the target class that would sneakily provide access to the internals...
推荐答案
在PHP中,您可以使用Reflections来做到这一点。
要调用受保护的方法或私有方法,请使用setAccessible()方法
http://php.net /reflectionmethod.setaccessible (只需将其设置为TRUE)
In PHP you can do this using Reflections. To invoke protected or private methods use the setAccessible() method http://php.net/reflectionmethod.setaccessible (just set it to TRUE)
这篇关于从PHP的类外部调用受保护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!