Skip to content

Initializing class property in get hook does not call set hook #17181

@everstead-it

Description

@everstead-it

Description

The following code:

<?php

class Deferred {
    // 
}

class Test {
    protected(set) array $loaded = [];
    
    protected(set) Deferred $instance {
        get => $this->instance ??= new Deferred();
        set {
            $this->instance = $value;
            $this->loaded[$value::class] = $value;
        }
    }
}

$test = new Test();

$instance = $test->instance;
var_dump($test->loaded);

Resulted in this output:

array(0) {
}

But I expected this output instead:

array(1) {
  ["Deferred"]=>
  object(Deferred)#? (0) {
  }
}

Here is the 3v4l.org link.

Is this expected behavior? I wanted to defer loading some objects until the property is requested, but I need to register them with a container instance whenever they are set.

PHP Version

PHP 8.4.1

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