PHP getopt Operations

后端 未结 3 1657
梦如初夏
梦如初夏 2021-01-11 19:19

This question is regarding getopt function in php. I need to pass two parameter to the php scripts like

php script.php -f filename -t filetype
3条回答
  •  囚心锁ツ
    2021-01-11 19:44

    I implemented a getopt parser for this, support short,long option names, type constraint, option printing.. etc. and this library has been maintained over 6 years.

    Synopsis:

    add( 'f|foo:' , 'option require value' );  # returns spec object.
    
    $options->add( 'b|bar+' , 'option with multiple value' );
    $options->add( 'z|zoo?' , 'option with optional value' );
    
    $options->add( 'f|foo:=i' , 'option require value, with integer type' );
    $options->add( 'f|foo:=s' , 'option require value, with string type' );
    
    $options->add( 'v|verbose' , 'verbose flag' );
    $options->add( 'd|debug'   , 'debug flag' );
    
    $parser = new OptionParser;
    $result = $parser->parse( array( 'program' , '-f' , 'foo value' , '-v' , '-d' ) );
    
    $result = $parser->parse( $argv );
    
    $spec = $result->verbose;
    $spec = $result->debug;
    $spec->value;  # get value
    

    GetOptionKit\OptionPrinter can print options for you:

    * Available options:
                  -f, --foo   option requires a value.
                  -b, --bar   option with multiple value.
                  -z, --zoo   option with optional value.
              -v, --verbose   verbose message.
                -d, --debug   debug message.
                     --long   long option name only.
                         -s   short option name only.
    

    Demo

    Please check examples/demo.php.

    Run:

    % php examples/demo.php -f test -b 123 -b 333
    

    Print:

    * Available options:
          -f, --foo     option requires a value.
         -b, --bar +    option with multiple value.
        -z, --zoo []    option with optional value.
              -v, --verbose    verbose message.
                -d, --debug    debug message.
                     --long    long option name only.
                         -s    short option name only.
    Enabled options: 
    * key:foo      spec:-f, --foo   desc:option requires a value.
        value => test
    
    * key:bar      spec:-b, --bar +  desc:option with multiple value.
        Array
        (
            [0] => 123
            [1] => 333
        )
    

    GetOptionKit is on GitHub: https://github.com/c9s/GetOptionKit

提交回复
热议问题