Ad

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.

Code
Diff
  • 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 KATA
    • static $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();
    • }