생성자 (__construct)
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 91개 중 7번째.
__construct 메서드는 새로운 객체를 생성할 때 자동으로 실행되는 특별한 메서드입니다. 이 메서드는 객체의 속성을 초기화합니다.
다음은 생성자가 포함된 클래스의 예입니다:
<?php
class Dog {
public $name;
public $breed;
public function __construct($name, $breed) {
$this->name = $name;
$this->breed = $breed;
}
}__construct 메서드는 매개변수를 받아 $this를 사용하여 이를 속성에 할당합니다.
생성자를 사용하여 객체를 생성합니다:
$rex = new Dog("Rex", "German Shepherd");
$buddy = new Dog("Buddy", "Golden Retriever");new Dog("Rex", "German Shepherd")를 호출하면, PHP는 자동으로 __construct를 호출하고 인수를 전달합니다.
생성자에 의해 설정된 속성에 액세스합니다:
echo $rex->name . "\n";
echo $rex->breed . "\n";
echo $buddy->name . "\n";
echo $buddy->breed . "\n";출력:
Rex
German Shepherd
Buddy
Golden Retriever기본 매개변수 값을 갖는 생성자를 가질 수도 있습니다:
class Cat {
public $name;
public $age;
public function __construct($name, $age = 1) {
$this->name = $name;
$this->age = $age;
}
}
$fluffy = new Cat("Fluffy", 3);
$whiskers = new Cat("Whiskers"); // age의 기본값은 1입니다
echo $fluffy->name . " is " . $fluffy->age . " years old\n";
echo $whiskers->name . " is " . $whiskers->age . " years old\n";출력:
Fluffy is 3 years old
Whiskers is 1 years old핵심 포인트: __construct 메서드는 객체가 생성될 때 모든 객체가 초기 데이터와 함께 적절하게 설정되도록 보장합니다. 이는 객체 생성 후 수동으로 속성을 설정해야 하는 번거로움을 줄여줍니다.
챌린지
쉬움도서 시스템을 구현하기 위해 PHP 파일(book.php 및 driver.php)이 제공됩니다.
당신의 작업은 다음과 같습니다:
book.php파일의Book클래스에서$title,$author,$pages속성을 초기화하는__construct메서드를 완성합니다.driver.php에서"Harry Potter", 저자"J.K. Rowling", 페이지 수400인 도서 객체를 임포트하고 생성합니다.
각 파일의 TODO 주석을 따르세요.
치트 시트
__construct 메서드는 새로운 객체를 생성할 때 속성을 초기화하기 위해 자동으로 실행되는 특별한 메서드입니다.
클래스 내에 생성자를 정의합니다:
<?php
class Dog {
public $name;
public $breed;
public function __construct($name, $breed) {
$this->name = $name;
$this->breed = $breed;
}
}생성자를 사용하여 객체를 생성합니다:
$rex = new Dog("Rex", "German Shepherd");
$buddy = new Dog("Buddy", "Golden Retriever");생성자에 의해 설정된 속성에 접근합니다:
echo $rex->name; // Rex
echo $rex->breed; // German Shepherd생성자는 기본 매개변수 값을 가질 수 있습니다:
class Cat {
public $name;
public $age;
public function __construct($name, $age = 1) {
$this->name = $name;
$this->age = $age;
}
}
$fluffy = new Cat("Fluffy", 3);
$whiskers = new Cat("Whiskers"); // age의 기본값은 1입니다직접 해보기
<?php
require_once 'book.php';
// TODO: 다음 속성을 가진 Book 객체를 생성하세요:
// title: "Harry Potter", author: "J.K. Rowling", pages: 400
$myBook = ?;
echo "'" . $myBook->title . "' by " . $myBook->author . ", " . $myBook->pages . " pages\n";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
8매직 메서드
매직 메서드 소개__toString 및 __debugInfo__get, __set, __isset, __unset__call 및 __callStatic__clone 및 객체 복제__serialize 및 __unserialize요약 - 커스텀 컬렉션