대충이라도 하자

PHP의 Magic Method 본문

꼬꼬마 개발자 노트/PHP

PHP의 Magic Method

Sueeeeee
반응형

**** 먼저, 오버로딩에 대해서 알아보자.

: overloading 은 매개변수의 개수와 타입을 달리하여 같은 이름의 메소드를 중복하여 정의 하는 것

ex) addValue(string name)

     addValue(string, name, int age)

=> 이런 식으로 자바에서는 같은 이름의 메소드지만 arguments가 다르기에 사용 가능

 

But, PHP에서는 다른 언어와는 달리 프로퍼티나 메소드를 동적으로 '생성한다'는 의미로 오버로딩을 사용 

 

 

 

"Magic methods are special methods which override PHP's default's action

when certain actions are performed on an object."

- 매직 메소드는 항상 클래스에 정의되어 있는 메소드들을 말하며, 이중 밑줄(__)로 시작

- 사용자가 직접 호출하는 것이 아니고, 특정 행동을 취했을 경우 호출되는 콜백함수 같은 것

- Method, Property, Serialize

 

1. Method

- __call(string, array ) : 클래스 내부에 정의되지 않은 메서드를 호출했을 경우, 해당 매직 메소드를 호출

 

-__callStatic(string, array) : 클래스 내부에 정의되지 않은 정적 메소드를 호출했을 경우, 호출

 

- __invoke(array) : 인스턴스 자체를 호출했을 경우, 호출

 

2. Property

- __set(string, mixed) : setter로, 클래스의 inaccessible property 값을 지정했을 때 실행

 

- __get(string) : getter로, 클래스의 inaccessible property 값을 조회했을 때 실행

 

-__isset(string) : booelan타입으로 return, 변수 값이 설정되었는지 확인

 

-__unset(string) : void 타입으로 return, unset a given variable ,

                      In a method, if a global variable is unset(), only local variable is destroyed.

 

3. Serialize

=> serialize(mixed $value) : string

=> 유형과 구조를 잃지 않고 PHP 값을 저장하거나 전달하는 데 유용

     example : N (null) / b:1 (boolean true) / b : 1 (boolean false) 

=>To make the serialized string into a PHP value again, use unserialize().

 

 

- __sleep() : array : serialize() 호출 시 호출된다. Firstyl, check if a class has a __sleep method. 

                         return an array of the names of all variables of an object that should be serialized.

-__wakeup() : unserialize()시 호출. 

 

 

===========================================================

__construct : 생성자로 클래스 인스턴스화 시 처음으로 호출

__destruct : 클래스의 소멸자로 인스턴스 파괴 시 호출된다.

 

반응형
Comments