Can PHP monkeypatch functions be replaced?

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

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

eg:.

 <? function var_dump() {} ?> Fatal error: Cannot redeclare var_dump() in /tmp/- on line 1 
+15
function php monkeypatching
Feb 10 '09 at 0:24
source share
6 answers

It's a bit late, but I just want to note that with PHP 5.3, you can actually override internal functions without using the PHP extension.

The trick is that you can override the inner function of PHP inside the namespace. It is based on a method for determining the name of a PHP for functions:

Inside a namespace (for example, A \ B), calls to unskilled functions are resolved at run time. Here's how the foo () function call is allowed:

  • It is looking for a function from the current namespace: A \ B \ foo ().
  • It tries to find and call the global function foo ()
+11
Aug 08 '13 at 7:23
source share

No, this is impossible to do, as you might expect.

From manual :

PHP does not support function overloading, nor is it possible to define or override 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 ?> 

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

+9
Feb 10 '09 at 0:25
source share

I understand this question is a bit outdated, but Patchwork is a recently released PHP 5.3 project that supports overriding custom functions. Although, as the author notes, you will need to resort to runkit or php-test-helpers in the kernel / library function of the monkey pattern.

+5
Nov 02 '10 at 14:45
source share
+2
Feb 10 '09 at 0:25
source share

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

Here is an article on how this 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 slightly better code because it does not use the eval () 'd code, unlike the patchwork game. You can cache op codes when using eval ().

+1
Apr 27 2018-12-12T00:
source share

The accepted answer is excellent !!! I just add that you can put your codes in namespace brackets , and then GLOBAL-SPACE is executed by default.

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

0
Nov 17 '16 at 20:35
source share



All Articles