소개
객체지향 프로그래밍 용어에서 생성자는 객체 생성 시 자동으로 호출되는 클래스 내부에 정의된 메소드이다. 생성자 메서드의 목적은 객체를 초기화하는 것입니다. PHP에서 특별한 이름의 메소드 __construct 생성자 역할을 합니다.
구문
__construct ([ mixed $args = "" [, $... ]] ) : void
생성자 예제
이 예제는 객체가 선언될 때 생성자가 자동으로 실행됨을 보여줍니다.
예시
<?php
class myclass{
function __construct(){
echo "object initialized";
}
}
$obj=new myclass();
?> 출력
그러면 다음과 같은 결과가 생성됩니다. -
object initialized
인수 생성자
클래스 속성은 인수가 있는 생성자에 의해 초기화됩니다.
예시
<?php
class rectangle{
var $height;
var $width;
function __construct($arg1, $arg2){
$this->height=$arg1;
$this->width=$arg2;
}
function show(){
echo "Height=$this->height Width=$this->width";
}
}
$obj=new rectangle(10,20);
$obj->show();
?> 출력
그러면 다음과 같은 결과가 생성됩니다. -
Height=10 Width=20
상속의 생성자
상위 클래스에 생성자가 정의되어 있으면 parent::__construct에 의해 하위 클래스의 생성자 내에서 호출될 수 있습니다. . 그러나 자식 클래스가 생성자를 정의하지 않으면 기본 클래스와 동일한 것을 상속합니다.
예시
<?php
class a{
function __construct(){
echo "this is a constructor of base class\n";
}
}
class b extends a{
function __construct(){
parent::__construct();
echo "this a constructor class b\n";
}
}
class c extends a {
//
}
$a=new a();
$b=new b();
$c=new c();
?> 출력
그러면 다음과 같은 결과가 생성됩니다. -
this is a constructor of base class this is a constructor of base class this a constructor class b this is a constructor of base class
소멸자
소멸자는 가비지 수집기가 특정 개체에 더 이상 참조가 없음을 확인하자마자 자동으로 메서드입니다. PHP에서 소멸자 메서드의 이름은 __destruct입니다. . 종료 시퀀스 동안에도 개체가 파괴됩니다. 소멸자 메서드는 인수를 사용하지 않으며 데이터 유형을 반환하지도 않습니다.
예시
<?php
class myclass{
function __construct(){
echo "object is initialized\n";
}
function __destruct(){
echo "object is destroyed\n";
}
}
$obj=new myclass();
?> 출력
다음 결과가 표시됩니다.
object is initialized object is destroyed