라이브러리

[PHP] GenderGender::__construct - Gender 객체 구성




PHP Class의 생성자


PHP의 생성자는 `__construct` 메서드입니다. 이 메서드는 클래스의 객체를 초기화하는 역할을 합니다. 생성자는 클래스의 속성을 초기화하고, 필요한 초기화 작업을 수행합니다.

예제: Gender Class


#hostingforum.kr
php

// Gender.php



class Gender {

    private $name;

    private $description;



    /

     * 생성자

     * @param string $name

     * @param string $description

     */

    public function __construct($name, $description) {

        $this->name = $name;

        $this->description = $description;

    }



    

     * 이름을 반환합니다.

     * @return string

     */

    public function getName() {

        return $this->name;

    }



    /**

     * 설명을 반환합니다.

     * @return string

     */

    public function getDescription() {

        return $this->description;

    }

}



예제 사용


#hostingforum.kr
php

// main.php



require_once 'Gender.php';



$male = new Gender('남성', '남성의 설명입니다.');

$female = new Gender('여성', '여성의 설명입니다.');



echo $male->getName() . "
"; // 남성

echo $male->getDescription() . "
"; // 남성의 설명입니다.

echo $female->getName() . "
"; // 여성

echo $female->getDescription() . "
"; // 여성의 설명입니다.



생성자와 속성 초기화


생성자는 클래스의 속성을 초기화하는 역할을 합니다. 위의 예제에서 `Gender` 클래스의 `name`과 `description` 속성을 초기화하는 생성자가 있습니다.

#hostingforum.kr
php

public function __construct($name, $description) {

    $this->name = $name;

    $this->description = $description;

}



생성자와 초기화


생성자는 클래스의 초기화 작업을 수행하는 역할을 합니다. 위의 예제에서 `Gender` 클래스의 초기화 작업은 `name`과 `description` 속성을 초기화하는 것입니다.

생성자와 오버로딩


생성자는 오버로딩이 가능합니다. 오버로딩은 동일한 이름의 메서드가 여러 개 존재할 수 있는 것을 말합니다. 위의 예제에서 `Gender` 클래스의 생성자가 여러 개 존재할 수 있습니다.

#hostingforum.kr
php

public function __construct($name) {

    $this->name = $name;

}



public function __construct($name, $description) {

    $this->name = $name;

    $this->description = $description;

}



생성자와 타입 힌트


PHP 7.0부터는 타입 힌트가 가능합니다. 타입 힌트는 함수의 매개변수 타입을 지정하는 것을 말합니다. 위의 예제에서 `Gender` 클래스의 생성자가 타입 힌트를 사용할 수 있습니다.

#hostingforum.kr
php

public function __construct(string $name, string $description) {

    $this->name = $name;

    $this->description = $description;

}



생성자와 디폴트 매개변수


PHP 5.6부터는 디폴트 매개변수가 가능합니다. 디폴트 매개변수는 함수의 매개변수에 디폴트 값을 지정하는 것을 말합니다. 위의 예제에서 `Gender` 클래스의 생성자가 디폴트 매개변수를 사용할 수 있습니다.

#hostingforum.kr
php

public function __construct(string $name, string $description = '') {

    $this->name = $name;

    $this->description = $description;

}


  • profile_image
    나우호스팅 @pcs8404 

    호스팅포럼 화이팅!

    댓글목록

    등록된 댓글이 없습니다.

  • 전체 10,077건 / 533 페이지

검색

게시물 검색