In my opinion, the command-line interfaces for PHP are sadly lacking. To meet expectations for users and programmers, 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 faithful to the spirit of his original port. This was a relatively easy task because Java and PHP5 are similar. Currently, the only thing it lacks is multilingual support. For that feature, I hope to get assistance from the international community.
The GNU Getopt package consists of two class files:
gnu/getopt/Getopt.php
gnu/getopt/Longopt.php
To install the package, copy the top-level gnu directory into your include 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.
The bundle contains a demo program named ‘optdemo’. Here’s the code from that program:
#!/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");
}
}
?>
As you can see, the implementation is pretty straightforward. The array of Longopt objects is optional. Each Longopt should contain a corresponding short opt in the Getopt class. Short opts are constructed exactly as you’d expect. Consider the option string “a:bc:d:hW;” Each option, preceded by a colon, expects an argument. In this case ‘a’, ‘c’ and ‘d’ all require an argument while ‘b’ and ‘h’ do not. The getopts method is an iterator. You can loop through the options and handle them in a loop similar to the one shown in the example.
The software is available here: GNU Getopt For PHP
Happy hacking
Here’s a Croatian translation of this page for our friends in the Balkans…