是否可以替换(monkeypatch)PHP 函数? [英] Is it possible to replace (monkeypatch) PHP functions?
问题描述
您可以在 Python 中执行此操作,但在 PHP 中可以吗?
<预><代码>>>>def a(): 打印 1...>>>def a(): 打印 2...>>>一种()2例如:
<代码>致命错误:无法在第 1 行的/tmp/- 中重新声明 var_dump()
这有点 晚了,但我只想指出,从 PHP 5.3 开始,实际上可以覆盖内部函数不使用 PHP 扩展.
诀窍是您可以在命名空间内重新定义内部 PHP 函数.它基于 PHP 对函数进行名称解析的方式:
在命名空间内(比如 AB),对非限定函数的调用在运行时被解析.以下是对函数 foo() 的调用是如何解析的:
- 它从当前命名空间中寻找一个函数:ABfoo().
- 它尝试查找并调用全局函数 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 AB), calls to unqualified functions are resolved at run-time. Here is how a call to function foo() is resolved:
- It looks for a function from the current namespace: ABfoo().
- It tries to find and call the global function foo()
这篇关于是否可以替换(monkeypatch)PHP 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!