__construct 메서드

__construct 메서드는 새로운 객체가 생성될 때 자동으로 호출되는 특별한 클래스 메서드입니다. 객체의 속성을 초기화하거나 다른 초기 설정을 수행하는 데 사용됩니다. 일반 메서드와 달리 생성자는 명시적으로 호출할 필요가 없습니다.

구문

phpclass ClassName {
  public function __construct([parameters]) {
    // initialization code
  }
}

예시

$name 속성을 설정하는 생성자를 가진 간단한 클래스를 만들어 보겠습니다:

php<?php
class User {
  public $name;
  
  public function __construct($name) {
    $this->name = $name;
  }
}

$user = new User('John');
echo $user->name;
?>

코드 실행 결과:

php'John'

예시

생성자는 여러 매개변수를 받고 복잡한 초기화를 수행할 수 있습니다:

php<?php
class Product {
  public $id;
  public $price;
  
  public function __construct($id, $price) {
    $this->id = $id;
    $this->price = $price * 1.2; // 20% 부가세 추가
  }
}

$product = new Product(101, 100);
echo $product->price;
?>

코드 실행 결과:

php120

함께 보기

  • 객체가 소멸될 때 호출되는 메서드 __destruct
  • 객체가 복제될 때 호출되는 메서드 __clone