PHPackages                             robier/mock-global-php-functions - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. robier/mock-global-php-functions

ActiveLibrary[Testing &amp; Quality](/categories/testing)

robier/mock-global-php-functions
================================

Mock any function that exists in global namespace

v1.0.1(3y ago)317.7k1MITPHPPHP &gt;=7.3

Since Apr 19Pushed 3y ago1 watchersCompare

[ Source](https://github.com/robier/mock-global-php-functions)[ Packagist](https://packagist.org/packages/robier/mock-global-php-functions)[ RSS](/packages/robier-mock-global-php-functions/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (2)Dependencies (1)Versions (3)Used By (0)

 [![Build Status](https://github.com/robier/mock-global-php-functions/actions/workflows/test.yml/badge.svg)](https://github.com/robier/mock-global-php-functions/actions/workflows/test.yml/badge.svg) [ ![](https://camo.githubusercontent.com/758dfcb0d6c9255aa67384085254bd94b1987492643802340e0cc24e3e1bee64/68747470733a2f2f636f6465636f762e696f2f67682f726f626965722f6d6f636b2d676c6f62616c2d7068702d66756e6374696f6e732f6272616e63682f6d61737465722f67726170682f62616467652e737667) ](https://codecov.io/gh/robier/mock-global-php-functions) [ ![MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667) ](https://travis-ci.org/robier/mock-global-php-functions)

Mock global php functions
-------------------------

[](#mock-global-php-functions)

This library allows you to mock any global PHP functions to return predefined values.

This library was created after I saw implementation of Symfony's [ClockMock](https://github.com/symfony/symfony/blob/4.2/src/Symfony/Bridge/PhpUnit/ClockMock.php)component for mocking PHP native functions related to time. I was curious how to make a mechanism for mocking any PHP global function, so I created this small library.

This is achieved by [PHP's namespace fallback policy](http://php.net/manual/en/language.namespaces.fallback.php):

> PHP will fall back to global functions \[…\] if a namespaced function \[…\] does not exist.

Library uses mentioned feature to dynamically create namespaced function. For this library to work your code that you are testing should be in **non global namespace** context and call function **unqualified**. For example:

```
namespace foo;

$time = time(); // This call can be mocked, a call to \time() can't.
```

Known limitations
-----------------

[](#known-limitations)

- Only **unqualified** function calls in a namespace context can be mocked. For example a call for `time()` in the namespace `foo` is mockable, a call for `\time()` is not.
- The mock has to be defined before the first call to the unqualified function in the tested class. This is documented in [Bug #68541](https://bugs.php.net/bug.php?id=68541). In most cases, you can ignore this limitation as you only need to define a mock before any testing in your tests. It's also recommend that you **run your tests as isolated process**.

### Api

[](#api)

At the moment there are 2 mocking objects that developers can use:

- `MockFunction` - mock any given function with your own anonymous function
- `FreezeClock` - mock time/sleep/date related functions, so they are in sync

### MockFunction

[](#mockfunction)

Object that can mock any function from global namespace. Mock is active as long as magic method `__destruct`is not called on that mock, or it's disabled manually via `disable` method. In that way you do not need to manually turn off mock while writing tests, because as soon as current scope exists, mock is disabled, and you have clean slate.

**Note:** When creating mock use static callback instead of regular one. This prevents them from having the current class automatically bound to them.

Example:

```
// mock is active as soon it's defined
$mock = new MockFunction('app', 'rand', static function(){
    return 5;
});

namespace app {
    // some logic
    $randomNumber = rand(); // random number will be always 5
    // some logic
}
```

Example of mocking sleep function:

```
$mock = new MockFunction('app', 'sleep', static function(){
    return 0;
});

namespace app {
    // some logic
    sleep(100); // sleep will not wait for 100 seconds as function is mocked
    // some logic
}
```

### FreezeClock

[](#freezeclock)

Handy object that can freeze time in given namespace.

Handy factory methods:

- `atZero` - stops time at timestamp 0
- `atTime` - stops time at provided time
- `atMicrotime` - stops time at provided microtime
- `atNow` - stops at current time

Functions affected:

- `date` - returns freeze formatted time
- `time` - return freeze time
- `microtime` - return freeze microtime
- `sleep` - increase freeze time and it's not blocking like regular sleep function
- `usleep` - increase freeze time and it's not blocking like regular usleep function

```
use Robier\MockGlobalFunction\FreezeClock;

$mock = new FreezeClock::atZero('app/testNamespace');

\app\testNamespace\sleep(15);

\app\testNamespace\time(); // would return 15
\app\testNamespace\microtime(true); // would return 15.0 also
```

### Tests

[](#tests)

First run `docker/build` to build a container and then `docker/run composer run test` for running all tests.

### Contribution

[](#contribution)

Feel free to contribute!

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity28

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~257 days

Total

2

Last Release

1223d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3d9bba20aad9bd9427b5ab4908e8370e81d913e11f2aeab24e948cde6be03bcd?d=identicon)[robier](/maintainers/robier)

---

Top Contributors

[![robier](https://avatars.githubusercontent.com/u/3607521?v=4)](https://github.com/robier "robier (6 commits)")

---

Tags

mockfunctionglobalmock timemock sleep

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/robier-mock-global-php-functions/health.svg)

```
[![Health](https://phpackages.com/badges/robier-mock-global-php-functions/health.svg)](https://phpackages.com/packages/robier-mock-global-php-functions)
```

###  Alternatives

[mockery/mockery

Mockery is a simple yet flexible PHP mock object framework

10.7k497.0M23.4k](/packages/mockery-mockery)[phpspec/prophecy

Highly opinionated mocking framework for PHP 5.3+

8.5k551.7M677](/packages/phpspec-prophecy)[php-mock/php-mock

PHP-Mock can mock built-in PHP functions (e.g. time()). PHP-Mock relies on PHP's namespace fallback policy. No further extension is needed.

36918.1M97](/packages/php-mock-php-mock)[php-mock/php-mock-phpunit

Mock built-in PHP functions (e.g. time()) with PHPUnit. This package relies on PHP's namespace fallback policy. No further extension is needed.

1718.2M395](/packages/php-mock-php-mock-phpunit)[phake/phake

The Phake mock testing library

4758.0M322](/packages/phake-phake)[kahlan/kahlan

The PHP Test Framework for Freedom, Truth and Justice.

1.2k1.2M245](/packages/kahlan-kahlan)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
