tetsunosukeのnotebook

tetsunosukeのメモです

PEAR::Console_Getoptでコマンドラインオプション解析

やっぱりPHPにもありました。

#!/usr/bin/php -q
<?php
require_once 'Console/Getopt.php';
$obj = new Console_Getopt();
$args = $obj->readPHPArgv();
$short = null;
$long = array('aaaa=', 'bbbb=');
$res = $obj->getopt($args, $short, $long);

if(PEAR::isError($res)){
    die ($res->getMessage() . "\n");
}

list($options, $others) = $res;
print_r($options);
print_r($others);
?>

これを

./work.php --aaaa=value1 --bbbb=value2 others

のように実行すると

こんな感じに。

Array
(
    [0] => Array
        (
            [0] => --aaaa
            [1] => value1
        )

    [1] => Array
        (
            [0] => --bbbb
            [1] => value2
        )

)
Array
(
    [0] => others
)

optionsの方をforeachでまわして、switchで分岐すればよさげ。