2007年6月3日星期日

使用 Zend_Console_Getopt 处理 PHP 命令行

Linux 下写Shell只要在第一行加上
#!/path/to/php
然后将脚本加上执行属性即可 chmod +x

注意:Windows下编程再上传的朋友要注意。换行必须以linux格式,否则脚本会报错

require_once 'Zend/Console/Getopt.php';

定义规则:

使用短语
$opts = new Zend_Console_Getopt('abp:');

使用长语法
$opts = new Zend_Console_Getopt(
array(
'apple|a' => 'This option chooses apple, with no parameter',
'banana|b=i' => 'This option chooses banana, with required integer parameter',
'pear|p-s' => 'This option chooses pear, with optional string parameter'
)
);


捕获异常
try {
$opts = new Zend_Console_Getopt('abp:');
$opts->parse();
} catch (Zend_Console_Getopt_Exception $e) {
echo $e->getUsageMessage();
exit;
}


获取命令行选项和参数
$b = $opts->getOption('b');
$p = $opts->getOption('p');


另一种方法是使用 __get() and __isset() 魔术方法
if (isset($opts->b)) {
echo "I got the b option.\n";
}
$p = $opts->p; // null if not set

没有评论: