是否可以替换(monkeypatch)PHP 函数? [英] Is it possible to replace (monkeypatch) PHP functions?

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

问题描述

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

<预><代码>>>>def a(): 打印 1...>>>def a(): 打印 2...>>>一种()2

例如:

<代码>致命错误:无法在第 1 行的/tmp/- 中重新声明 var_dump()

解决方案

有点 晚了,但我只想指出,从 PHP 5.3 开始,实际上可以覆盖内部函数不使用 PHP 扩展.

诀窍是您可以在命名空间内重新定义内部 PHP 函数.它基于 PHP 对函数进行名称解析的方式:

在命名空间内(比如 AB),对非限定函数的调用在运行时被解析.以下是对函数 foo() 的调用是如何解析的:

  1. 它从当前命名空间中寻找一个函数:ABfoo().
  2. 它尝试查找并调用全局函数 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:

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

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

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