Created
October 19, 2015 12:33
-
-
Save ts0818/b59cb6cd6d706ab4d3e1 to your computer and use it in GitHub Desktop.
パーフェクトphpのオーバーロード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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