PHP code example of dlin / getopt

1. Go to this page and download the library: Download dlin/getopt 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/ */

    

dlin / getopt example snippets


$getOpt = new GetOpt();
$getOpt->setOption(array('arg'=>'s'));
$getOpt->setOption(array('arg'=>'t'));

$getOpt->parse();

//php myScript.php -s 10 -t int foo bar zee

echo $getOpt->t; // output int
echo $getOpt->s; // output 10
echo $getOpt->foo; //null
echo $getOpt->nonexist; //null



//php myScript.php -s 10 -t int foo bar zee

echo $getOpt->_; //Array with values ['foo', 'bar', 'zee']

//php myScript.php --s 10 -type int   (wrong)

echo $getOpt->s; // null
echo $getOpt->type; // null
echo $getOpt->_; //Array, ['--s', '10', '-type', int]

//php myScript.php -s 10 --type int   (the right way)

echo $getOpt->s; // 10
echo $getOpt->type; // int
echo $getOpt->_; //Array, [ ]



$getOpt = new GetOpt();

$getOpt->setOption(array('arg'=>'s', 'alias'=>'size')); //normal
$getOpt->setOption(array('arg'=>'type', 'alias'=>'t')); //this also work

//php myScript.php -s 10 -t int foo bar zee
//or
//php myScript.php --size 10 -t int foo bar zee
//or
//php myScript.php --size 10 --type int foo bar zee

echo $getOpt->t; // output int
echo $getOpt->type; // output int
echo $getOpt->s; // output 10
echo $getOpt->size; // output 10



Usage: php myScript.php

Options:
	-s,size	 	Size of generated array
	-t,type		Type of items in the generated array



$reportFunc = function($msg){ echo touppercase($msg); };

$exitFunc = function(){}; //do not terminate

$inputFunc = function(){/* read and return a line from a file instead */ };

...
$getopt = new Getopt(null, $reportFunc , $existFunc, $inputFunc);
...


$this->reportFunction =  function ($msg) {
    echo $msg;
    echo "\n";
};
$this->exitFunction =  function () {
    exit;
};
$this->inputFunction =   function () {
    return trim(fgets(STDIN));
};