Command Line Subcommands in PHP
Here’s the translation of the Go code to PHP, maintaining the structure and explanations:
Our first program demonstrates how to use command-line subcommands in PHP. Here’s the full source code:
<?php
// We'll use the getopt function to parse command-line arguments
function parseArgs($args) {
return getopt('', ['enable::', 'name:', 'level:'], $args);
}
function main($argc, $argv) {
// The subcommand is expected as the first argument to the program
if ($argc < 2) {
echo "expected 'foo' or 'bar' subcommands\n";
exit(1);
}
// Check which subcommand is invoked
switch ($argv[1]) {
// For every subcommand, we parse its own flags and
// have access to trailing positional arguments
case 'foo':
$options = parseArgs(array_slice($argv, 2));
$enable = isset($options['enable']);
$name = $options['name'] ?? '';
$tail = array_slice($argv, count($options) + 2);
echo "subcommand 'foo'\n";
echo " enable: " . ($enable ? 'true' : 'false') . "\n";
echo " name: $name\n";
echo " tail: " . implode(' ', $tail) . "\n";
break;
case 'bar':
$options = parseArgs(array_slice($argv, 2));
$level = $options['level'] ?? 0;
$tail = array_slice($argv, count($options) + 2);
echo "subcommand 'bar'\n";
echo " level: $level\n";
echo " tail: " . implode(' ', $tail) . "\n";
break;
default:
echo "expected 'foo' or 'bar' subcommands\n";
exit(1);
}
}
main($argc, $argv);
Save this script as command-line-subcommands.php
.
First, invoke the foo subcommand:
$ php command-line-subcommands.php foo --enable --name=joe a1 a2
subcommand 'foo'
enable: true
name: joe
tail: a1 a2
Now try bar:
$ php command-line-subcommands.php bar --level 8 a1
subcommand 'bar'
level: 8
tail: a1
But bar won’t accept foo’s flags:
$ php command-line-subcommands.php bar --enable a1
subcommand 'bar'
level: 0
tail: --enable a1
Note that in PHP, unlike Go, we don’t have built-in support for subcommands. We’ve simulated this behavior by manually parsing the arguments and using a switch statement to handle different subcommands. The getopt
function is used to parse command-line options, but it doesn’t provide the same level of structure as Go’s flag
package. As a result, our PHP implementation is more basic and doesn’t provide the same level of error checking and usage information as the Go version.
Next, we’ll look at environment variables, another common way to parameterize programs.