このプログラムはPHP5.3以上で動作します。
name = $name;
}
// getter
public function __get($property){
if( in_array($property, $this->_getters) ){
return $this->$property;
}
if( in_array($property, $this->_setters) ){
throw new Exception("このプロパティは読み取り専用です");
}
throw new Exception($property . "は存在しません");
}
// setter
public function __set($property, $value) {
if( in_array($property, $this->_setters) ){
$this->$property = $value;
}
if( in_array($property, $this->_getters) ){
throw new Exception("このプロパティは書き込み専用です");
}
throw new Exception($property . "は存在しません");
}
}
C#でいうところの public string Test { get; set; } と同じです。
Userクラスのインスタンスを生成して ->(アロー演算子)で ->Nameと呼び出せばOKです。
内部で存在しないプロパティを指定すると例外が発生するようになっています。