Is it possible to replace (monkeypatch) PHP functions?

你离开我真会死。 提交于 2019-11-26 19:03:32

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

No, it is not possible to do this as you might expect.

From the manual:

PHP does not support function overloading, nor is it possible to undefine or redefine previously-declared functions.

HOWEVER, You can use runkit_function_redefine and its cousins, but it is definitely not very elegant...

You can also use create_function to do something like this:

<?php
$func = create_function('$a,$b','return $a + $b;');
echo $func(3,5); // 8
$func = create_function('$a,$b','return $a * $b;');
echo $func(3,5); // 15
?>

As with runkit, it is not very elegant, but it gives the behavior you are looking for.

I realize this question is a bit old, but Patchwork is a recently-released PHP 5.3 project that supports redefinition of user-defined functions. Though, as the author mentions, you will need to resort to runkit or php-test-helpers to monkey-patch core/library functions.

As jmikola mentioned, Patchwork is a good solution if you want to add code to a function.

Here's an article about how it works: http://phpmyweb.net/2012/04/26/write-an-awesome-plugin-system-in-php/

It comes with some sample code. I think the phpmyweb version uses a slightly better code, because he doesn't use eval()'d code, unlike patchwork. You can cache opcodes when using eval().

T.Todua

The accepted answer is excellent!!! I will just add,that you can put your codes in Namespace brackets and then the default GLOBAL-SPACE is resetted.

some other ways:

1) rename_function($old_name,$new_name)

2) override_function($old_name, $parameters, $new_func)

and rarely used:

3) runkit_function_rename(...)

4) runkit_function_redefine(...)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!