Abs
Abs

Reputation: 57916

Redefine Built in PHP Functions

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?

Upvotes: 19

Views: 18935

Answers (3)

Markus Malkusch
Markus Malkusch

Reputation: 7868

echo is not a function, it's a language construct. I don't have anything for that.

But function calls like time() can be overridden since PHP-5.3's namespace fallback policy:

For functions […], PHP will fall back to global functions […] if a namespaced function […] does not exist.

E.g. for the unqualified function call time() in the non global namespace foo you can provide foo\time().

Personally I'm using this to mock e.g. time() for unit test. I published those mocks in the library PHP-Mock:

namespace foo;

use phpmock\phpunit\PHPMock;

class FooTest extends \PHPUnit_Framework_TestCase
{

    use PHPMock;

    public function testBar()
    {
        $time = $this->getFunctionMock(__NAMESPACE__, "time");
        $time->expects($this->once())->willReturn(3);
        $this->assertEquals(3, time());
    }
}

Upvotes: 1

Gordon
Gordon

Reputation: 316969

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

Upvotes: 6

Johannes Gorset
Johannes Gorset

Reputation: 8785

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.

Upvotes: 18

Related Questions