PHP OOP - 생성자
PHP - __construct 함수
생성자를 사용하면 객체 생성 시 객체의 속성을 초기화할 수 있습니다.
함수를 생성 __construct()
하면 클래스에서 객체를 생성할 때 PHP가 자동으로 이 함수를 호출합니다.
구성 함수는 두 개의 밑줄(__)로 시작합니다!
아래 예에서 생성자를 사용하면 코드 양을 줄이는 set_name() 메서드를 호출하지 않아도 된다는 것을 알 수 있습니다.
예시
<?php
class Fruit {
public
$name;
public $color;
function __construct($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit("Apple");
echo $apple->get_name();
?>
또 다른 예:
예시
<?php
class Fruit {
public
$name;
public $color;
function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
function get_name() {
return $this->name;
}
function get_color() {
return $this->color;
}
}
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
echo
"<br>";
echo $apple->get_color();
?>