久々にPHPで開発
みたいな事やってみた。
これ拡張すればjavascriptとかrubyみたいにメソッドチェインでガシガシ書ける。
だた気になったのはマジックメソッドの__toStringがStringでしか使えないって事。
こういうの
N = new Integer(1);
print(N);
でstringじゃなくてintの返しが欲しいっす
PHPの偉い人。__toNumberみたいなマジックメソッド作って下さい。
今回はintObj->get()みたいな事して対応してます。
<?php /** * extends SPL ErrorException Object * @class ConvertErrorException extends ErrorException * * @method __construct * @method getErrorMessage */ class ConvertErrorException extends ErrorException { public function __construct($message) { $this->message = $message; } public function getErrorMessage() { return $this->message; } } /** * @class Converter extends ConvertErrorException * * @method __construct * @method toString * @method toNumber * @method equals * @method get * @method __destruct */ class Converter extends ConvertErrorException { protected $value; protected $bool; public function __construct() {} public function toString() { $this->value = (string)$this->value; return new String($this->value); } public function toNumber() { $this->value = (int)$this->value; return new Integer($this->value); } public function equals($str) { return $this->value === $str->get() ? true : false; } public function get() { return $this->value; } public function __destruct() {} } /** * @class Integer extends Converter * * @method __construct * @method __destruct * */ class Integer extends Converter { public function __construct($value) { $this->value = $value; } public function __destruct() { } } /** * @class String extends Converter * * @method __construct * @method replace * */ class String extends Converter { public function __construct($value) { $this->value = $value; } public function __toString() { # magic method return $this->value; } public function replace($old, $new) { if (preg_match("/^\/[^\/]+\/.*$/", $patt)) { return new String(preg_replace($old, $new, $this->value)); } else { return new String(str_replace($old, $new, $this->value)); } } } /** * @class Boolean * * @method __construct * @method ifTrue * @method ifFalse * */ class Boolean { private $bool; public function __construct($bool) { $this->bool = $bool; } public function ifTrue() { return $this->bool === true ? true : false; } public function ifFalse() { return $this->bool === false ? true : false; } } function main () { $i = new Integer(1); $s = new String("1"); var_dump( $i->get(), $s->toNumber()->get(), $s->equals($i) ); var_dump($s->toString()->replace("1","1000000")->get()); var_dump($i instanceof Integer); var_dump($s instanceof String); } try { main(); } catch(ConvertErrorException $e) { var_dump($e); } catch(exception $e) { var_dump($e); } ?>
あとfinallyも欲しいな
前に作ったみたいなのを実装するとかめんどいなぁ・・・