PHP 8.4 Property hooks 문법으로 약한 참조 편하게 쓰기

PHP에서는 WeakReference 클래스를 사용해서 약한 참조를 쓸 수 있다.

그런데 약한 참조를 쓰게 되면 약한 참조에 해당하는 객체를 사용할 때 코딩이 번거롭다. WeakReference::create()로 만든 객체에서 get() 메서드를 호출해야 해당 객체를 쓸 수 있기 때문이다.

$obj = new stdClass();
$weakref = WeakReference::create($obj);
var_dump($weakref->get());

이에 아래와 같이 Property hooks 문법을 활용하여 강한 참조 쓰듯이 약한 참조를 편하게 사용할 수 있다.

class Foo
{
    public function hello(): void
    {
        echo 'hello' . PHP_EOL;
    }
}

class Bar
{
    /** @var \WeakReference<\Foo> */
    private \WeakReference $_foo;

    public private(set) ?Foo $foo {
        get => $this->_foo->get();
        set {
            $this->_foo = \WeakReference::create($value);
        }
    }

    public function __construct(\Foo $foo)
    {
        $this->foo = $foo;
    }
}

$foo = new \Foo();
$bar = new \Bar($foo);

$bar->foo->hello(); // hello

var_dump($bar->foo); // object(Foo)#1 (0) {}
unset($foo);
var_dump($bar->foo); // NULL

 

이 글은 개발 카테고리에 분류되었고 태그가 있으며 님에 의해 에 작성되었습니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다