In PHPUnit, how can a cache be implemented to avoid side effects across test method instances?

When running multiple test methods in PHPUnit, the state of objects can persist between test method instances, causing side effects. To avoid this, a cache can be implemented to store and retrieve objects used in tests, ensuring each test method starts with a clean state. This can be achieved by using a static variable to store the cached objects and a setup method to initialize the cache before each test method.

class MyTest extends \PHPUnit\Framework\TestCase
{
    private static $cache = [];

    protected function setUp(): void
    {
        self::$cache = [];
    }

    public function testMethod1()
    {
        // Use self::$cache to store and retrieve objects
    }

    public function testMethod2()
    {
        // Use self::$cache to store and retrieve objects
    }
}