In my opinion, the command line interfaces for PHP are sadly lacking. To meet expectations for the user and the programmer it’s best to follow established standards. Whenever possible, a programmer should follow POSIX guidelines. Yet in many cases GNU extensions are preferred and expected. To meet these expectations, I’ve ported GNU Getopt to php.
This package is based on the 1998 Java port of Getopt by Aaron M. Renn. Whenever possible, I tried to remain true to the spirit of his original port. This was a relatively easy task due to the similarities between java and php5. Currently, the only thing it’s lacking is multiple language support. For that feature, I’m hope to get assistance from the international community.
To install the package, copt the top-level gnu directory into your inclue path. To find the directories included in that path, run the following at the command line:
php -r "echo ini_get('include_path');"
In my case, the result was ‘.:/usr/share/pear:/usr/share/php’ To install the package, I copied ‘gnu’ into /usr/share/php.
#!/usr/bin/php <?php require_once("gnu/getopt/Getopt.php"); require_once("gnu/getopt/Longopt.php"); $longopt = array(); $longopt[0] = new LongOpt("help", NO_ARGUMENT, null, 'h'); $longopt[1] = new LongOpt("about", REQUIRED_ARGUMENT, null, 'a'); $getopt = new Getopt($argv, "a:bc:d:hW;", $longopt); $c; $arg; while (($c = $getopt->getopts()) != -1) { switch($c) { case 'a': case 'd': $arg = $getopt->getOptarg(); print( "You picked $c with an argument of ".(($arg != null) ? $arg : "null")."n" ); break; case 'b': case 'c': $arg = $getopt->getOptarg(); print( "You picked $c with an argument of ".(($arg != null) ? $arg : "null")."n" ); break; case 'h': print "Usage: test [options] n"; break; case '?': break; // getopt() already printed an error default: print("getopt() returned $cn"); } } ?>
The software is available here: GNU Getopt For PHP
Happy hacking
Here’s a Croation Translation of this page for our friends in the Balkans….