null合体演算子 ?? を使うとかなり綺麗に書けることに気づいた
<? $opts = getopt("c:a:w:g"); $cmd = $opts["c"] ?? ""; $address = $opts["a"] ?? ""; $waittime = intval($opts["w"] ?? "0"); $debug = isset($opts["g"]);
issetの羅列にならないのは良い
ただし、値の無いオプションは依然としてissetが必要
オプションが存在するときに 値が false になる件
これについて「なんでPHPはオプションありがfalseなんだよクソァ!!」とキレてる人がいる
Be sure to wrap your head around this PHP jewel that took me a while to comprehend:
The returned array will contain a boolean FALSE for options that HAVE been specified.
Because why use TRUE to indicate "yes, it's there" when you can also use FALSE for that purpose, right? This is completely counter-intuitive and is most certainly only ever possible in PHP-land.
https://www.php.net/manual/ja/function.getopt.php
これは「値が必須ではないオプション」が原因で、「オプションがセットされているが値は無い」を表すのに false を使用しているから。
しかしこの「値が必須ではないオプション」とかいう誰も使いそうもない機能をサポートしてるのがそもそも良くない話だと思う。