로그인

검색

php 객체의 메서드(함수) 중에 생성자 메서드가 있는데 이 생성자 메서드의 역할은 각 객체(인스턴스)를 초기화 해주는 역할을 합니다.

 

 

<?php

class Entree {
    public $name;
    public $ingredients = array();

 

    public function hasIngredient($ingredient) {
        return in_array($ingredient, $this->ingredients);
    }
}

 

위 Entree class 에는 생성자 메서드가 없습니다.

 

여기에 추가를 한다면

<?php

class Entree {
    public $name;
    public $ingredients = array();

 

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

 

    public function hasIngredient($ingredient) {
        return in_array($ingredient, $this->ingredients);
    }
}

 

위와 같이 생성자 메서드가 추가될 수 있습니다.

생성자 메서드(함수)의 이름은 항상 __construct 로 고정으로 사용합니다.

 

이렇게 해주면 객체를 생성할때 생성자 메서드를 호출하는 형식을 사용할 수 있습니다.

생성자 메서드를 호출한다고 해서 함수의 결과가 반환되거나 하지는 않습니다. 해당 인스턴스(객체)에 사용할 인수를 전달하고 이 전달된 인수를 해당 객체에서 사용하도록 해 주는 것이라고 이해했습니다.

 

생성자 메서드가 없는 경우는 

$soup = new Entree;

$soup->name = '닭고기 수프';
$soup->ingredients = array('닭고기', '물');

 

이런식으로 인스턴스(객체)를 생성했습니다.

 

 

그런데 생성자 메서드가 있는 class의 경우는 생성자 메서드를 호출하면 필요한 인수를 전달할 수 있습니다.

 

$soup = new Entree('닭고기 수프', array('닭고기', '물'));

 

이렇게 생성자 메서드를 호출하는 형식으로 객체를 생성할 수 있습니다.

new 지시자에 의해 Entree class의 생성자 메서드를 괄호() 안의 인수를 전달하여 객체를 생성하는 것 입니다.

 

 

이렇게 전달된 인수를 

$this->name = $name;
$this->ingredients = $ingredients;

 

이렇게 $this 에 정의를 해서 지금 현재 객체의 변수로 사용이 되도록 한 것 입니다.

Who's 꿀팁관리소장

profile
라이믹스로 커뮤니티 사이트를 운영하는 비개발자 운영자 입니다.
파트너쉽 맺으실 사이트 운영자분 환영합니다.
2 추천

php 기초지식(24)

php를 학습할 수 있습니다.

  1. read more
  2. read more
  3. php 객체 확장

    Date2021.09.20 Views161 Votes2
    Read More
  4. php 객체 생성자 __construct 메서드

    Date2021.09.17 Views403 Votes2
    Read More
  5. Read More
  6. php 객체 지향의 이해 4

    Date2021.09.12 Views215 Votes2
    Read More
  7. php isset()

    Date2021.09.11 Views109 Votes2
    Read More
  8. php 변수의 영역 전역변수와 지역변수

    Date2021.08.29 Views1573 Votes2
    Read More
  9. php 함수의 반환값

    Date2021.08.28 Views140 Votes2
    Read More
  10. php 함수의 기초

    Date2021.08.25 Views161 Votes2
    Read More
  11. php 다차원 배열

    Date2021.08.14 Views415 Votes2
    Read More
  12. Read More
  13. Read More
  14. php 배열의 원소 제거 unset()

    Date2021.08.08 Views292 Votes2
    Read More
  15. Read More
  16. Read More
  17. php 배열(array)

    Date2021.07.31 Views149 Votes2
    Read More
  18. php 반복문 for, while

    Date2021.07.28 Views385 Votes2
    Read More
  19. php 증감 연산자 ++, -- 3

    Date2021.07.27 Views200 Votes2
    Read More
  20. 활용이 가장 많은 중요한 if 조건문 3

    Date2021.07.26 Views188 Votes2
    Read More
  21. php 이스케이프 \(역슬래쉬) 사용 1

    Date2021.07.24 Views638 Votes2
    Read More
  22. Read More
Prev 1 2 Next
/ 2