DrPep
DrPep

Reputation: 350

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 file_get_contents() or print_r()) and the likes?

Upvotes: 3

Views: 4599

Answers (4)

Markus Malkusch
Markus Malkusch

Reputation: 7878

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().

Upvotes: 0

user187291
user187291

Reputation: 53950

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.

Upvotes: 2

Ricket
Ricket

Reputation: 34077

If by "stub" you mean replace, there is a PHP override_function function; it's part of PECL though. You can also rename them.

Upvotes: 3

Amy B
Amy B

Reputation: 17977

You aren't clear about what 'stub' means.

Do you mean getting doc for functions, like:

/**
 * (PHP 5 &gt;= 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) {}

?

Upvotes: 0

Related Questions