在PHP中,动态调用静态方法时使用forward_static_call_array()而不是call_user_func_array()有什么优点吗?
具体来说,一个比另一个更有效率吗?
Specifically, is one more efficient than the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
forward_static_call_array
和call_user_func_array
:之后,我想有与 PHP 5.3 中引入的后期静态绑定相关的一些差异。
实际上,如果您仔细查看给定的示例,似乎确实如此:您在其中使用
forward_static_call_array
的类的“上下文”在被调用的方法中被“保留”。考虑到这部分代码,它是从给定的示例派生出来的:
您将得到以下输出:
即从类 A 中的方法,您通过
static::
关键字“知道”,您'重新“来自B”。现在,如果您尝试使用
call_user_func
执行相同的操作:(代码的其余部分不会更改)
您将得到以下输出:
请注意 A 在第二行!使用
forward_static_call_array
,您没有得到A,而是得到B。这就是区别:
forward_static_call_array
将静态上下文转发到被调用的方法,而call_user_func_array
则不会。关于你的效率问题:我不知道——你必须进行基准测试;但这实际上不是重点:重点是这两个函数不做同样的事情。
There is at leat two differences between
forward_static_call_array
andcall_user_func_array
:After that, I suppose there is some difference that's related to Late Static Binding, that was introduced with PHP 5.3.
Actually, if you take a closer look at the given example, it seems to be exactly that : the "context" of the class inside which you are using
forward_static_call_array
is "kept", in the called method.Considering this portion of code, that's derived from the given example :
You'll get this output :
i.e. from the method in class A, you "know", via the
static::
keyword, that you're "coming from B".Now, if you try to do the the same thing with
call_user_func
:(the rest of the code doesn't change)
You'll get this output :
Note the A on the second line ! With
forward_static_call_array
, you didn't get an A, but a B.That's the difference :
forward_static_call_array
forwards the static context to the method that's called, whilecall_user_func_array
doesn't.About your efficiency question : I have no idea -- you'd have to benchmark ; but that's really not the point : the point is that those two functions don't do the same thing.