Don't reinitialize static property, instead, reference it.
During first execution, it'll be created with a null
value. Right after creation, since it's null
the Null Coalescing Assignment Operator will give us a new anonymous class and return a new instance of itself.
On following executions, the static property will be referenced, and since it already exists, it will not be reset to null
. Since it's not null
, the class assignment will be skipped, and will jump right to return a new instance.
function a() { static $poi; $poi ??= new class { public function create() { return new static(); } }; return $poi->create(); }
function a(){// We shall remove the following solution when publish as KATAstatic $poi = null;if ($poi) return $poi->create();$poi = new class {- function a() {
- static $poi;
- $poi ??= new class {
- public function create() {
- return new static();
- }
- };
- return $poi->create();
- }
class AnonymousClassTest extends TestCase { public function testSameClassName() { $this->assertSame(get_class(a()), get_class(a())); } public function testAnonymous() { $this->assertSame(0, strpos(get_class(a()), "class@anonymous")); } public function testDifferentIns() { $this->assertSame(a() !== a(), true); } }
// PHPUnit Test Examples:// TODO: Replace examples and use TDD development by writing your own testsclass MyTestCases extends TestCase- class AnonymousClassTest extends TestCase
- {
// test function names should start with "test"- public function testSameClassName() {
- $this->assertSame(get_class(a()), get_class(a()));
- }
- public function testAnonymous() {
- $this->assertSame(0, strpos(get_class(a()), "class@anonymous"));
- }
- public function testDifferentIns() {
- $this->assertSame(a() !== a(), true);
- }
- }