GNU Getopt For PHP

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.

The GNU Getopt package consists of two class files:

gnu/getopt/Getopt.php

gnu/getopt/Longopt.php

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.

The bundle contains a demo program named ‘optdemo’. Here’s the code from that program:

As you can see, the implementation is pretty straight forward. The array of Longopt objects are 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 proceded 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.