PHP OOP - 소멸자
PHP - __destruct 함수
소멸자는 객체가 소멸되거나 스크립트가 중지되거나 종료될 때 호출됩니다.
함수 를 생성하면 __destruct()
PHP는 스크립트 끝에서 자동으로 이 함수를 호출합니다.
destruct 함수는 두 개의 밑줄(__)로 시작합니다!
아래 예제에는 클래스에서 객체를 생성할 때 자동으로 호출되는 __construct() 함수와 스크립트 끝에서 자동으로 호출되는 __destruct() 함수가 있습니다.
예시
<?php
class Fruit {
public
$name;
public $color;
function __construct($name) {
$this->name = $name;
}
function __destruct() {
echo "The fruit is {$this->name}.";
}
}
$apple = new Fruit("Apple");
?>
또 다른 예:
예시
<?php
class Fruit {
public
$name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function __destruct() {
echo "The fruit is {$this->name}
and the color is {$this->color}.";
}
}
$apple = new Fruit("Apple", "red");
?>
팁: 생성자와 소멸자는 코드 양을 줄이는 데 도움이 되므로 매우 유용합니다!