毎日PHP書くといいがち書いてなかったので今日はPHPも書きます。
7つの言語7つの世界、Rubyのp33で出てた例は美しかったけどなんか、これだと微妙です。
見た目が美しくない。
This file contains hidden or 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 | |
class Roman | |
{ | |
public static function __callStatic($name, $args) | |
{ | |
$roman = $name; | |
$roman = preg_replace('/IV/', 'IIII', $roman); | |
$roman = preg_replace('/IX/', 'VIIII', $roman); | |
$roman = preg_replace('/XL/', 'XXXX', $roman); | |
$roman = preg_replace('/XC/', 'LXXXX', $roman); | |
return (preg_match_all('/I/', $roman, $out) + | |
preg_match_all('/V/', $roman, $out) * 5 + | |
preg_match_all('/X/', $roman, $out) * 10 + | |
preg_match_all('/L/', $roman, $out) * 50 + | |
preg_match_all('/C/', $roman, $out) * 100); | |
} | |
} | |
echo Roman::X(), PHP_EOL; | |
echo Roman::XC(), PHP_EOL; | |
echo Roman::XII(), PHP_EOL; | |
echo Roman::X(), PHP_EOL; |
マジックメソッドの__callStaticで、呼び出したメソッドの名前(ローマ数字)を数に変換して返しています。
0 件のコメント:
コメントを投稿