Redefine Built in PHP Functions

Viewed 17429

I would like to redefine certain functions in PHP that are already built for example, echo() or time() - I don't need to define these functions globally, just within a single script for testing.

I think this can be done in Perl but in PHP - Is this possible?

3 Answers

runkit_function_redefine — Replace a function definition with a new implementation

Note: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.

You might also want to check out

override_function() — Overrides built-in functions

from the Advanced PHP debugger package.

Having to redefine native PHP functions or language statements should ring an alarm bell though. This should not be part of your production code in my opinion, unless you are writing a debugger or similar tool.

Another option would be to use http://antecedent.github.io/patchwork

Patchwork is a PHP library that makes it possible to redefine user-defined functions and methods at runtime, loosely replicating the functionality runkit_function_redefine in pure PHP 5.3 code, which, among other things, enables you to replace static and private methods with test doubles.

The latter doesn't work for native functions though

Related