PHP code example of chh / optparse

1. Go to this page and download the library: Download chh/optparse library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chh / optparse example snippets




HH\Optparse;

$parser = new Optparse\Parser("Says Hello");

function usage_and_exit()
{
    global $parser;
    fwrite(STDERR, "{$parser->usage()}\n");
    exit(1);
}

$parser->addFlag("help", array("alias" => "-h"), "usage_and_exit");
$parser->addFlag("shout", array("alias" => "-S"));
$parser->addArgument("name", array("



$parser = new CHH\Optparse\Parser;

$parser->addFlag("help");
$parser->parse();

if ($parser["help"]) {
    echo $parser->usage();
    exit;
}


$parser->addFlag("help", ["alias" => "-h"]);



$parser->addFlag("name", ["has_value" => true]);
$parser->parse(['--name', 'John']);

echo "Hello World {$parser["name"]}!\n";



$parser->addFlag("pid_file", ["default" => "/var/tmp/foo.pid", "has_value" => true]);

$parser->parse([]);

echo "{$parser["pid_file"]}\n";
// Output:
// /var/tmp/foo.pid



$foo = null;
$bar = null;

$parser->addFlag("foo", ["var" => &$foo, "has_value" => true]);
$parser->addFlagVar("bar", $bar, ["has_value" => true]);

$parser->parse(['--foo', 'foo', '--bar', 'bar']);

echo "$foo\n";
echo "$bar\n";
// Output:
// foo
// bar



$parser = new Parser;

function usage_and_exit()
{
    global $parser;
    echo $parser->usage(), "\n";
    exit;
}

$parser->addFlag("help", ['alias' => '-h'], "usage_and_exit");

$parser->addFlag("queues", ["has_value" => true], function(&$value) {
    $value = explode(',', $value);
});



$parser->addArgument("files", ["var_arg" => true]);

// Will always be null, because the value will be consumed by the
// "var_arg" enabled argument.
$parser->addArgument("foo");

$parser->parse(["foo", "bar", "baz"]);

foreach ($parser["files"] as $file) {
    echo $file, "\n";
}
// Output:
// foo
// bar
// baz



$parser->addArgument("foo");
$parser->parse(["foo", "bar", "baz"]);

echo var_export($parser->args());
// Output:
// array("foo", "bar", "baz")

// Can also be used to fetch named arguments:
echo var_export($parser->arg(0));
echo var_export($parser->arg("foo"));
// Output:
// "foo"
// "foo"

// Pass start and length:
echo var_export($parser->slice(0, 2));
// Output:
// array("foo", "bar");