PHPでプロパティ

naohiro19
記事: 256
登録日時: 14年前
住所: 愛知県

PHPでプロパティ

投稿記事 by naohiro19 » 9年前

PHPで以下のような User クラスが定義してあります。
このプログラムはPHP5.3以上で動作します。

CODE:

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 . "は存在しません");
    }

}
private に宣言されている $nameは Userクラス以外からは呼び出せません。そこで、役立つのが __setと__getです。
C#でいうところの public string Test { get; set; } と同じです。
Userクラスのインスタンスを生成して ->(アロー演算子)で ->Nameと呼び出せばOKです。
内部で存在しないプロパティを指定すると例外が発生するようになっています。

CODE:

Name = "テストユーザー";
echo $user->Name;
 // →「テストユーザー」と表示されます
$user->ip = "127.0.0.1"; 
 //→「ipは存在しません」と表示
?>
最後に編集したユーザー naohiro19 on 2016年7月15日(金) 21:12 [ 編集 3 回目 ]

コメントはまだありません。