Redefine Built in PHP Functions

匿名 (未验证) 提交于 2019-12-03 01:20:02

问题:

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?

回答1:

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.



回答2:

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



回答3:

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());     } } 


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