phpunit-globals icon indicating copy to clipboard operation
phpunit-globals copied to clipboard

Allows to use attributes to define global variables in PHPUnit test cases

PHPUnit Globals

Allows to use annotations to define global variables in PHPUnit test cases.

Build Status

Supported annotations:

  • @env for $_ENV
  • @server for $_SERVER
  • @putenv for putenv()

Global variables are set before each test case is executed, and brought to the original state after each test case has finished. The same applies to putenv()/getenv() calls.



composer require --dev zalas/phpunit-globals


The extension is also distributed as a PHAR, which can be downloaded from the most recent Github Release.

Put the extension in your PHPUnit extensions directory. Remember to instruct PHPUnit to load extensions in your phpunit.xml:

<phpunit xmlns:xsi="" xsi:noNamespaceSchemaLocation=""


Enable the globals annotation extension in your PHPUnit configuration:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi=""

    <!-- ... -->

        <extension class="Zalas\PHPUnit\Globals\AnnotationExtension" />


Make sure the AnnotationExtension is registered before any other extensions that might depend on global variables.

Global variables can now be defined in annotations:

use PHPUnit\Framework\TestCase;

 * @env FOO=bar
class ExampleTest extends TestCase
     * @env APP_ENV=foo
     * @env APP_DEBUG=0
     * @server APP_ENV=bar
     * @server APP_DEBUG=1
     * @putenv APP_HOST=localhost
    public function test_global_variables()
        $this->assertSame('bar', $_ENV['FOO']);
        $this->assertSame('foo', $_ENV['APP_ENV']);
        $this->assertSame('0', $_ENV['APP_DEBUG']);
        $this->assertSame('bar', $_SERVER['APP_ENV']);
        $this->assertSame('1', $_SERVER['APP_DEBUG']);
        $this->assertSame('localhost', \getenv('APP_HOST'));

Updating to PHPUnit 8

When updating from a previous version of this extension that used to work with PHPUnit older than v8, replace the listener registration in phpunit.xml:

        <listener class="Zalas\PHPUnit\Globals\AnnotationListener" />

with the extension registration:

        <extension class="Zalas\PHPUnit\Globals\AnnotationExtension" />


Please read the Contributing guide to learn about contributing to this project. Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.