Skip to content

Instantly share code, notes, and snippets.

@ts0818
Created October 19, 2015 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ts0818/b59cb6cd6d706ab4d3e1 to your computer and use it in GitHub Desktop.
Save ts0818/b59cb6cd6d706ab4d3e1 to your computer and use it in GitHub Desktop.
パーフェクトphpのオーバーロード
<?php
/* クラスSomeClassを定義 */
class SomeClass{
// privateな値を保存するコンテナ(プロパティ)
private $values = array();
// privateなコンテナ(プロパティ)へのアクセサ(メソッド)getter
public function __get($name){
if(!isset($this->values[$name])){
throw new OutOfBoundsException($name."not found.");
}
return $this->values[$name];
}
// privateなコンテナ(プロパティ)へのアクセサ(メソッド)setter
public function __set($name, $value){
echo "set: $name setted to $value",PHP_EOL;
$this->values[$name] = $value;
}
public function __isset($name){
echo "isset: $name",PHP_EOL;
return isset($this->values[$name]);
}
public function __unset($name){
echo "unset: $name",PHP_EOL;
unset($this->values[$name]);
}
public function __call($name, $args){
echo "call: $name",PHP_EOL;
// アンダースコアをつけ、メソッド名とする
$method_name = '_' . $name;
if(!is_callable(array($this, $method_name))){
throw new BadMethodCallException($name . " method not found.");
}
return call_user_func_array(array($this, $method_name),$args);
}
public static function __callStatic($name, $args){
echo "callStatic: $name",PHP_EOL;
$method_name = '_' . $name;
if(!is_callable(array('self', $method_name))){
throw new BadMethodCallException($name . "method not found.");
}
return call_user_func_array(array('self',$method_name), $args);
}
private function _bar($value){
echo "bar called with arg '$value'", PHP_EOL;
}
private static function _staticBar($value){
echo "staticBar called with arg '$value'",PHP_EOL;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment