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