Creating the parser

Creating the parser – how to create a parser using PHP code or an XML definition file

Console_CommandLine constructor

Console_CommandLine::__construct() takes an optional array of parameters explained in the table below. Note that if you are using an XML definition file, you can pass these parameters in it (see XML example for details).

Available parameters
name type required description
name string no, default to $argv[0] if not given the name of your program
description string no, but recommended for the help message the description of your program: this should explain what your program is supposed to do
version mixed (string or numeric) no, note that if not given, the --version option will not be available the program version number
add_help_option boolean no, default to TRUE if set to FALSE the parser will not generate automatically the "help" option
add_version_option boolean no, default to TRUE if set to FALSE the parser will not generate automatically the "version" option
force_posix boolean no, default to FALSE if set to TRUE, the parser will force POSIX compliance (please see the gettext manual for more information)

Using PHP code

The examples below demonstrate how to instanciate Console_CommandLine and build a parser using PHP code.

The simplest way

<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine(array(
    
'description' => 'A useful description for your program.',
    
'version'     => '0.0.1'// the version of your program
));
?>

Alternative method

<?php
require_once 'Console/CommandLine.php';
$parser = new Console_CommandLine();
$parser->description 'A useful description for your program.';
$parser->version '0.0.1'// the version of your program
?>

Using an XML definition file

The examples below demonstrate how to instanciate Console_CommandLine and build a parser using an XML definition file, this can be very useful if you have a big program or if you need to reuse your user interface settings for a web frontend for example.

The XML file

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<command>
    <description>A useful description for your program.</description>
    <version>0.0.1</version>
</command>

The PHP file

<?php
require_once 'Console/CommandLine.php';
$parser Console_CommandLine::fromXmlFile('example.xml');
?>

Using an XML string you would have called Console_CommandLine::fromXmlString() instead of Console_CommandLine::fromXmlFile() of course.