Extended collection class not behaving the same as base collection class

If you put this code into tests/TestCase/CollectionTest.php, the test will fail.

namespace App\Test\TestCase;

use Cake\Collection\Collection;
use PHPUnit\Framework\TestCase;

class MyCollection extends Collection { }

class CollectionTest extends TestCase
    public function testIterators(): void {
        $records = [
            ['field' => true],
            ['field' => false],
            ['field' => true],

        $collection = new MyCollection($records);
        $count = 0;
        foreach ($collection as $investment) {
            $count ++;
            if ($count > 20) {
            if ($collection->every(fn ($record) => $record['field'] === true)) {
                // Nothing, really, just need to execute the every() call

        $this->assertEquals(3, $count);

But if you change new MyCollection to new Collection, it works just fine. I can’t figure why this is the case, when the MyCollection class here is literally nothing different from the base class. (Of course, in my actual use case, it has a few additional functions, but this is the minimum reproducible example.)

Seems like a bug inside the CollectionTrait.
The line which causes the problem is this one:

I’ll create an issue in the repo since this collection magic is out of my league…

Ah, that should maybe also be an instanceof.

edit: Confirmed that changing that line to $iterator instanceof Collection lets this particular test pass. Haven’t tried running the Cake test suite with that change; it may break other things?

It does break other things, thats why I created an issue, not a PR