코딩 스쿨 PHP

언어선택 : HTMLCSSJAVAJAVASCRIPTMYSQLSQL PHP

PHP Constructor

PHP 생성자(Constructor): 객체 초기화의 기본 가이드


  • *PHP 생성자(Constructor)**는 객체를 생성할 때 자동으로 호출되는 특별한 메서드로, 객체의 초기 상태를 설정하는 데 사용됩니다. 생성자는 객체가 만들어질 때 필요한 속성을 초기화하거나, 초기 작업을 수행하는 데 필수적입니다. PHP에서 생성자는 **__construct()*라는 이름을 가지며, 클래스가 인스턴스화될 때 자동으로 실행됩니다.

이 가이드에서는 PHP 생성자의 개념, 기본 사용법, 다중 생성자(메서드 오버로딩 대체)실용적인 예제를 다룹니다.


1. PHP 생성자란?

생성자는 객체가 생성될 때 실행되는 함수입니다. 클래스 내에서 **__construct()**로 정의되며, 객체를 초기화하는 데 사용됩니다. 생성자를 사용하면 객체가 생성될 때 특정 속성에 값을 설정할 수 있습니다.

1.1 기본 생성자 예제

<?php
class Car {
    public $color;
    public $model;

    // 생성자 정의
    public function __construct($color, $model) {
        $this->color = $color;
        $this->model = $model;
    }

    public function drive() {
        return "The $this->color $this->model is driving.";
    }
}

// 객체 생성 시 생성자 호출
$myCar = new Car("red", "Toyota");
echo $myCar->drive();  // 결과: The red Toyota is driving.
?>

설명:

  • __construct(): 생성자는 객체가 생성될 때 자동으로 호출되며, 여기서 객체의 속성(예: color, model)을 초기화합니다.
  • 객체 생성 시 **new Car("red", "Toyota")*를 통해 생성자가 호출됩니다.

2. 생성자의 역할

PHP 생성자의 주요 역할은 객체가 생성될 때 초기화 작업을 수행하는 것입니다. 객체가 생성되면서 필요한 데이터를 설정하거나, 특정 로직을 초기화할 수 있습니다.

2.1 기본 역할: 속성 초기화

<?php
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }

    public function greet() {
        return "Hello, my name is $this->name and I am $this->age years old.";
    }
}

$person = new Person("Alice", 30);
echo $person->greet();  // 결과: Hello, my name is Alice and I am 30 years old.
?>

설명:

  • 생성자는 객체가 생성될 때 속성을 초기화합니다. 이 예제에서는 nameage 속성이 생성자에 의해 초기화됩니다.

3. 기본값이 있는 생성자

생성자에서는 매개변수에 기본값을 설정할 수 있습니다. 기본값이 있는 생성자는 특정 매개변수가 제공되지 않을 때 기본값을 사용합니다.

3.1 기본값 설정

<?php
class Car {
    public $color;
    public $model;

    public function __construct($color = "white", $model = "Ford") {
        $this->color = $color;
        $this->model = $model;
    }

    public function drive() {
        return "The $this->color $this->model is driving.";
    }
}

// 객체 생성 시 기본값 사용
$defaultCar = new Car();
echo $defaultCar->drive();  // 결과: The white Ford is driving.

// 매개변수를 제공하여 기본값 덮어쓰기
$customCar = new Car("blue", "BMW");
echo $customCar->drive();  // 결과: The blue BMW is driving.
?>

설명:

  • 생성자의 매개변수에 기본값을 설정하여, 인스턴스를 생성할 때 매개변수가 제공되지 않으면 기본값을 사용합니다.

4. 생성자 오버로딩

PHP는 생성자 오버로딩(동일한 함수명을 가진 여러 생성자)을 직접 지원하지 않지만, 이를 구현하려면 매개변수의 개수를 확인하거나 조건문을 사용해 유사한 동작을 구현할 수 있습니다.

4.1 조건문을 사용한 다중 생성자 구현

<?php
class User {
    public $username;
    public $age;

    public function __construct() {
        $args = func_get_args();  // 전달된 인자 목록을 가져옴
        $numArgs = func_num_args();  // 전달된 인자 수

        if ($numArgs == 1) {
            $this->username = $args[0];
            $this->age = null;  // 기본값 설정
        } elseif ($numArgs == 2) {
            $this->username = $args[0];
            $this->age = $args[1];
        }
    }

    public function showInfo() {
        return "Username: $this->username, Age: $this->age";
    }
}

$user1 = new User("Alice");  // 매개변수 1개
echo $user1->showInfo();  // 결과: Username: Alice, Age:

$user2 = new User("Bob", 25);  // 매개변수 2개
echo $user2->showInfo();  // 결과: Username: Bob, Age: 25
?>

설명:

  • func_get_args(): 전달된 모든 인자를 배열로 가져옵니다.
  • func_num_args(): 전달된 인자의 개수를 반환합니다.
  • 조건문을 사용해 다중 생성자와 유사한 동작을 구현할 수 있습니다.

5. 부모 클래스 생성자 호출

상속된 클래스에서 부모 클래스의 생성자를 호출해야 할 때가 있습니다. 이를 위해 **parent::__construct()**를 사용하여 부모 생성자를 호출할 수 있습니다.

5.1 부모 생성자 호출

<?php
class Vehicle {
    public $brand;

    public function __construct($brand) {
        $this->brand = $brand;
    }
}

class Car extends Vehicle {
    public $model;

    // 자식 클래스의 생성자
    public function __construct($brand, $model) {
        parent::__construct($brand);  // 부모 클래스의 생성자 호출
        $this->model = $model;
    }

    public function display() {
        return "Brand: $this->brand, Model: $this->model";
    }
}

$myCar = new Car("Toyota", "Corolla");
echo $myCar->display();  // 결과: Brand: Toyota, Model: Corolla
?>

설명:

  • *parent::__construct()*를 사용하여 부모 클래스의 생성자를 호출할 수 있습니다.
  • 부모 클래스에서 상속된 속성을 초기화한 후, 자식 클래스의 속성도 초기화할 수 있습니다.

6. 소멸자(Destructor)

  • *소멸자(Destructor)**는 객체가 더 이상 필요하지 않을 때 자동으로 호출되는 메서드로, PHP에서 **__destruct()*로 정의됩니다. 주로 자원 해제종료 작업을 처리할 때 사용됩니다.

6.1 소멸자 예제

<?php
class Car {
    public $model;

    public function __construct($model) {
        $this->model = $model;
        echo "Car created: $this->model<br>";
    }

    // 소멸자 정의
    public function __destruct() {
        echo "Car destroyed: $this->model<br>";
    }
}

$myCar = new Car("Honda");
echo "Driving the car...<br>";
// $myCar가 스코프를 벗어나면 소멸자가 호출됩니다.
?>

결과:

Car created: Honda
Driving the car...
Car destroyed: Honda

설명:

  • *__destruct()*는 객체가 메모리에서 해제될 때 자동으로 호출됩니다. 이를 통해 객체가 제거되기 전 자원을 정리할 수 있습니다.

7. PHP 생성자 실용 예제

7.1 데이터베이스 연결 예제

<?php
class Database {
    private $host;
    private $username;
    private $password;
    private $connection;

    // 생성자에서 데이터베이스 연결 초기화
    public function __construct($host, $username, $password) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->connect();
    }

    // 데이터베이스 연결 메서드
    private function connect() {
        $this->connection = "Connected to $this->host with user $this->username";
    }

    public function getConnection() {
        return $this->connection;
    }

    // 소멸자에서 연결 해제
    public function __destruct() {
        echo "Connection closed.";

 }
}

// 객체 생성 시 데이터베이스 연결
$db = new Database("localhost", "root", "password");
echo $db->getConnection();  // 결과: Connected to localhost with user root
?>

설명:

  • 생성자에서 데이터베이스 연결과 같은 초기화 작업을 처리할 수 있습니다.
  • 소멸자에서 연결을 해제하거나 자원을 정리할 수 있습니다.

요약

PHP 생성자(Constructor)는 객체가 생성될 때 자동으로 호출되어 객체 초기화 작업을 수행합니다. __construct() 메서드를 사용하여 속성 값을 설정하거나, 필요한 초기 작업을 할 수 있습니다. 또한 다중 생성자와 같은 기능을 구현하기 위해 조건문을 사용하거나, 상속된 클래스에서 부모 생성자를 호출할 수도 있습니다. PHP 생성자는 객체 지향 프로그래밍에서 중요한 개념으로, 객체 초기화와 관련된 로직을 효율적으로 처리할 수 있습니다.


copyright ⓒ 스타트코딩 all rights reserved.
이메일 : startcodingim@gamil.com