-
class 에서 자기 자신을 instance하기php 2023. 10. 19. 09:11
클래스를 instance할 때, 자기 자신을 instance해서 클래스 내부의 함수를 사용하고싶다면 주의해야할 점이 있다.
class Test{ private $testObject; public function __construct() { $this->testObject = new Test(); } }
만일 다음과 같은 형태로 작성되어있는 class를 instance 한다면,
생성된 testObject 내부에서 또 testObject가 생성되는 무한 루프가 되어서 메모리를 소진시켜버린다..
class Test{ private $testObject; public function __construct() { $this->testObject = $this; } }
이를 방지하기 위해서 현재 instance 된 자기 자신 객체를 필드에 저장하도록 하자