Skip to content

Anonymous class extends protected constructor #10372

@josbert-m

Description

@josbert-m

Description

The following code:

<?php

namespace Tests\Unit\Definers;

use PHPUnit\Framework\TestCase;
use DI\Definers\Singleton;

class SingletonTest extends TestCase
{
    public function test_create_singleton(): void
    {
        $House = new class extends Singleton
        {
            public int $peoples = 0;

            protected function factory(): void
            {
                $this->peoples = 2;
            }
        };

        $house_instance = $House::get();

        $this->assertInstanceOf($House::class, $house_instance);
    }
}

The Singleton DI\Definers\Singleton code:

<?php

namespace DI\Definers;

class Singleton
{
    protected static self $instance;

    /**
     * Deny instancing
     */
    final protected function __construct() { }

    /**
     * Deny cloning
     */
    final protected function __clone(): void { }

    /**
     * Return singleton instance
     *
     * @return self
     */
    final public static function get(): self
    {
        if (!isset(static::$instance)) {
            static::$instance = new static();
        }

        return static::$instance;
    }
}

Resulted in this output:

There was 1 error:

1) Tests\Unit\Definers\SingletonTest::test_create_singleton
Error: Call to protected DI\Definers\Singleton::__construct() from scope Tests\Unit\Definers\SingletonTest

/home/josbert-m/php/packages/di/tests/Unit/Definers/SingletonTest.php:12

But I expected this output instead:

PHPUnit 9.6-dev by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 00:00.068, Memory: 6.00 MB

OK (1 test, 1 assertion)

When the extended class not is a anonymous class works, but this is not working

PHP Version

PHP 8.1.13

Operating System

Ubuntu 22.04

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions