PHP에는 __get(), __set()이란 특별한 매직메소드가 있습니다. 이 매직메소드의 사용에 대해서 여러 논란이 있기는 하지만, 개인적으로 적절히 사용을 한다면 매우 유용하다고 생각합니다. 매직 메소드를 구현하는 방법은 여러가지이지만 그 중 간단하면서도 유용한 코드 하나를 소개 합니다.
publicfunction__get($name){if(property_exists($this,$name)){return$this->{$name};}$method_name="get_{$name}";if(method_exists($this,$method_name)){return$this->{$method_name}();}trigger_error("Undefined property $name or method $method_name");}publicfunction__set($name,$value){if(property_exists($this,$name)){$this->{$name}=$value;return;}$method_name="set_{$name}";if(method_exists($this,$method_name)){$this->{$method_name}($value);return;}trigger_error("Undefined property $name or method $method_name");}
보여드린 코드는 이름이 맞는 변수가 있으면 그것을 get 또는 set 하고, 만약 변수가 없지만 get_foobar(), set_foobar()와 같은 메소드가 있으면 그것을 호출하는 방식입니다.
특별한 기능이 필요하지 않다면 위 메소드를 클래스에 넣어두는 것만으로 기본적인 프로퍼티에 대한 get, set 메소드의 구현은 끝나게 됩니다.
만약 프로퍼티 보다 get_foobar(), set_foobar()에 우선을 두어 동작시키고 싶다면 매직메소드 내에서 프로퍼티를 찾는 부분과 메소드를 찾는 부분의 if 문 위치를 서로 바꾸어 주면 됩니다. 이렇게 할 결우 특정한 메소드의 get, set 동작만 특별하게 변형시키고 싶을 때 유용합니다.