Yes, this is possible and done in a handful of places in core. One example is TimeTest
. I am not 100% sure it is official, but I call it a shadow function.
The trick is to declare the procedural function in the same namespace as the caller. As an example the Drupal\Component\Datetime\Time
class has a method
public function getCurrentTime() {
return time();
}
this calls out the PHP internal function time()
. TimeTest
sets up
namespace Drupal\Component\Datetime;
/**
* Shadow time() system call.
*
* @returns int
*/
function time() {
return 12345678;
}
When PHP chases the scope for resolving a reference, it will check the current namespace first. By declaring the namespace, the procedural function declaration ends up that namespace instead of the global one (\
). And since the test class only gets loaded during tests, you don't end up polluting the namespace with a bad function.
setUp
method of the test! drupal.org/docs/8/phpunit/…