Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to replace (monkeypatch) PHP functions?

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
like image 245
gak Avatar asked Feb 10 '09 00:02

gak


4 Answers

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()
like image 144
Silviu G Avatar answered Nov 02 '22 03:11

Silviu G


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.

like image 42
Paolo Bergantino Avatar answered Nov 02 '22 04:11

Paolo Bergantino


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.

like image 5
jmikola Avatar answered Nov 02 '22 04:11

jmikola


Kind of. See http://dev.kafol.net/2008/09/php-redefining-deleting-adding.html.

like image 1
Sophie Alpert Avatar answered Nov 02 '22 05:11

Sophie Alpert