Advanced PHP Programming -- 如何理解 Console/Getopt.php 的使用 P129

  開始沒怎麼理解short options 與 long options , 後來看了(http://pear.php.net/manual/en/package.console.console-getopt.examples.php)這個連接中的例子理解了。對“Console/Getopt.php”的瞭解也根據上面連接裏的內容。

  例子如下:

 

<?php
/**
 * Example how to get a key-value pair array
 * from command line parameters with Console_Getopt.
 *
 * @link http://pear.php.net/bugs/bug.php?id=13902
 */
require_once 'Console/Getopt.php';

/**
 * Make a key-value array.
 * Since Console_Getopt does not provide such a method,
 * we implement it ourselves.
 *
 * @params array $params Array of parameters from Console_Getopt::getopt2()
 *
 * @return array key-value pair array
 */
function &condense_arguments($params)
{
    $new_params = array();
    foreach ($params[0] as $param) {
        $new_params[$param[0]] = $param[1];
    }
    return $new_params;
}


$cg = new Console_Getopt();
$args = $cg->readPHPArgv();
array_shift($args);

$shortOpts = 'u:g:';
$longOpts  = array('user=', 'group=');

$params = $cg->getopt2($args, $shortOpts, $longOpts);
if (PEAR::isError($params)) {
    echo 'Error: ' . $params->getMessage() . "\n";
    exit(1);
}

var_dump(condense_arguments($params));
/*
When called as follows:
 associative.php -u jason -g argonauts
you will get this output:
 array(2) {
   ["u"]=>
   string(5) "jason"
   ["g"]=>
   string(9) "argonauts"
 }
 */
?> 


 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章