Stub PHP native methods
In my unit test, i'm looking to stub the behaviour of php's inbuilt file_get_contents() method.
Is there a way to stub native methods in PHP (such as fi开发者_如何学Pythonle_get_contents() or print_r()) and the likes?
If by "stub" you mean replace, there is a PHP override_function function; it's part of PECL though. You can also rename them.
It is possible with runkit. Use runkit_function_copy and runkit_function_redefine functions to copy and redefine functions. You should set the runkit.internal_override ini-setting to 1 in order to modify internal functions.
You aren't clear about what 'stub' means.
Do you mean getting doc for functions, like:
/**
* (PHP 5 >= 5.1.0)<br/>
* Sets the default timezone used by all date/time functions in a script
* @link http://php.net/manual/en/function.date-default-timezone-set.php
* @param timezone_identifier string <p>
* The timezone identifier, like UTC or
* Europe/Lisbon. The list of valid identifiers is
* available in the .
* </p>
* @return bool This function returns false if the
* timezone_identifier isn't valid, or true
* otherwise.
*/
function date_default_timezone_set ($timezone_identifier) {}
?
Since PHP-5.3's namespace fallback policy you can override calls to unqualified function names in a non global namespace context:
For functions […], PHP will fall back to global functions […] if a namespaced function […] does not exist.
I.e. a call to the unqualified function name file_get_contents()
in e.g. the namespace foo
can be overridden by providing a foo\file_get_contents()
.
I recently created the library PHP-Mock which provides mocks for some non deterministic PHP functions like time()
.
精彩评论