Is it possible to replace (monkeypatch) PHP functions?

前端 未结 6 786
感情败类
感情败类 2020-11-27 07:36

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

>>> def a(): print 1
... 
>>> def a(): print 2
... 
>>> a()
2
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 08:16

    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()

提交回复
热议问题