2

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?

DrPep
  • 330
  • 1
  • 4
  • 14
  • 1
    This question might help you http://stackoverflow.com/questions/2326835/redefine-built-in-php-functions – Mike B Mar 31 '10 at 13:43

4 Answers4

3

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

Ricket
  • 33,368
  • 30
  • 112
  • 143
2

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.

user187291
  • 53,363
  • 19
  • 95
  • 127
0

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) {}

?

Amy B
  • 17,874
  • 12
  • 64
  • 83
  • 2
    A `stub` is a stand-in for a method. You usually use it in UnitTests: http://www.phpunit.de/manual/current/en/test-doubles.html#test-doubles.mocking-the-filesystem and is a technical term: http://en.wikipedia.org/wiki/Method_stub – Gordon Mar 31 '10 at 13:53
  • Apologies for the lack of clarity; yes, I refer to the wikipedia definition of a method stub i.e. a standin for a method, which i'm looking to use in my unit test. – DrPep Mar 31 '10 at 13:58
0

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

Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67