<?phpclassFoobar{private$name;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");}}classMyFoobarextendsFoobar{private$age;}$foobar=newFoobar();$foobar->name="Foobar";echo"{$foobar->name}\n";$my_foobar=newMyFoobar();$my_foobar->age=42;$my_foobar->name="My Foobar";echo"{$my_foobar->name}\n";echo"{$my_foobar->age}\n";?>
실행을 시켜보면 __get() 메소드에서 ‘MyFoobar’ 클래스 멤버 변수 ‘$age’를 찾지 못 하는 것을 에러 메시지로 확인 할 수 있다. 이렇게 된 것은 __get() 메소드가 ‘Foobar’ 클래스 내에 존재하기 때문이다. 이를 해결하기 위해서는 __get(), __set() 메소드를 ‘MyFoobar’로 옮기면 되지만, 그런 경우 ‘Foobar’ 클래스에 문제가 생길뿐더라 전혀 아름다운 모습이 아니기도 하다.
그나마 조금 절충을 해 볼 수 있는 방법이 멤버 변수들은 ‘protected’로 바꾸고 ‘ReflectionProperty()’ 함수를 이용하는 것이다.
처음 의도한대로 멤버 함수를 private으로 유지하면서 자식 클래스에서 부모의 멤버 변수를 접근하는데 아무런 문제가 생기지 않는다.
다만 멤버 변수가 많은 경우 일일히 getter, setter를 입력하는 것이 번거로우므로 snippet을 생성하는 스크립트나 에디터의 snippet 생성 기능을 적극적으로 활용해서 반복적인 작업 시간을 절약하는 것이 좋을 듯 하다. 간단한 클래스 코드를 생성 해주는 페이지도 있으니 이것을 사용해도 괜찮다.