是否有可能取代(monkeypatch)PHP函数? [英] Is it possible to replace (monkeypatch) PHP functions?

查看:100
本文介绍了是否有可能取代(monkeypatch)PHP函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以在Python中执行此操作,但是可以在PHP中执行吗?

 >>> def a():print 1 
...
>>> def a():print 2
...
>>> a()
2

例如:

 <? function var_dump(){}?> 
致命错误:无法在第1行中重新声明/ tmp /中的var_dump()


解决方案 最近,我只想指出,自PHP 5.3以来,实际上可以在不使用PHP扩展的情况下覆盖内部函数。 p>

诀窍是您可以在名称空间内重新定义一个内部PHP函数。它基于PHP为函数命名解析的方式:



内部命名空间(比如A \ B),在运行时解析对非限定函数的调用。下面是如何解析函数foo()的调用:


  1. 它从当前名称空间查找函数:A \ B \\ \\foo()。它尝试查找并调用全局函数foo()


You can do this in Python, but is it possible in PHP?

>>> def a(): print 1
... 
>>> def a(): print 2
... 
>>> a()
2

e.g.:

<? function var_dump() {} ?>
Fatal error: Cannot redeclare var_dump() in /tmp/- on line 1

解决方案

This is a bit late, but I just want to point out that since PHP 5.3, it is actually possible to override internal functions without using a PHP extension.

The trick is that you can redefine an internal PHP function inside a namespace. It's based on the way PHP does name resolution for functions:

Inside namespace (say A\B), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved:

  1. It looks for a function from the current namespace: A\B\foo().
  2. It tries to find and call the global function foo()

这篇关于是否有可能取代(monkeypatch)PHP函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆