PHPackages                             toolkit/pflag - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. toolkit/pflag

ActiveLibrary[CLI &amp; Console](/categories/cli)

toolkit/pflag
=============

Command line flag parse library of the php

v2.0.7(1y ago)3438.4k—9.4%[1 issues](https://github.com/php-toolkit/pflag/issues)3MITPHPPHP &gt;8.0.0CI passing

Since Aug 25Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/php-toolkit/pflag)[ Packagist](https://packagist.org/packages/toolkit/pflag)[ Docs](https://github.com/php-toolkit/pflag)[ RSS](/packages/toolkit-pflag/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (2)Versions (22)Used By (3)

PHP Flag
========

[](#php-flag)

[![License](https://camo.githubusercontent.com/c6da716391cd4350fef23e0647d9ae1ef271d38c7a41c31120d44ed006686677/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f746f6f6c6b69742f70666c61672e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![GitHub tag (latest SemVer)](https://camo.githubusercontent.com/1db0673793dee71b8977a4b6533ca66f5e8dfaaf5bff805448d64a0a9fbd6f87/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f7461672f7068702d746f6f6c6b69742f70666c6167)](https://github.com/php-toolkit/pflag)[![Actions Status](https://github.com/php-toolkit/pflag/workflows/Unit-Tests/badge.svg)](https://github.com/php-toolkit/pflag/actions)[![Php Version Support](https://camo.githubusercontent.com/f28274d884921a8423b8730f6c41171e403ef7e94aa2cf4b90245c8cf05e83b3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f6f6c6b69742f70666c6167)](https://packagist.org/packages/toolkit/pflag)[![Latest Stable Version](https://camo.githubusercontent.com/ebce78077dc0d5a1b51d2090b398a403401914a83a5c37da5f84cc9718ec01eb/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f6f6c6b69742f70666c61672e737667)](https://packagist.org/packages/toolkit/pflag)[![Coverage Status](https://camo.githubusercontent.com/78047f81c8e81640c53aec8eb8c3c4844d88455548aeed3b79c935dc3f84241e/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f7068702d746f6f6c6b69742f70666c61672f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/php-toolkit/pflag?branch=main)[![zh-CN readme](https://camo.githubusercontent.com/aa09c729fc2ea6a01bd2ce90fcc0f6db764ca475c2c16e138c86d4ec4808521f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f2545342542382541442545362539362538372d526561646d652d627269676874677265656e2e7376673f7374796c653d666f722d7468652d6261646765266d61784167653d32353932303030)](README.zh-CN.md)

Generic PHP command line flags parse library

> Github: [php-toolkit/pflag](https://github.com/php-toolkit/pflag)

Features
--------

[](#features)

- Generic command line options and arguments parser.
- Support set value data type(`int,string,bool,array`), will auto format input value.
- Support set multi alias names for an option.
- Support set multi short names for an option.
- Support set default value for option/argument.
- Support read flag value from ENV var.
- Support set option/argument is required.
- Support set validator for check input value.
- Support auto render beautiful help message.

**Flag Options**:

- Options start with `-` or `--`, and the first character must be a letter
- Support long option. eg: `--long` `--long value`
- Support short option. eg: `-s -a value`
- Support define array option
    - eg: `--tag php --tag go` will get `tag: [php, go]`

**Flag Arguments**:

- Support binding named arguemnt
- Support define array argument

### Quick build command

[](#quick-build-command)

- Use `Toolkit\PFlag\CliCmd` to quickly build a simple command application
- Use `Toolkit\PFlag\CliApp` to quickly build a command application that supports subcommands

Install
-------

[](#install)

- Require PHP 8.0+

**composer**

```
composer require toolkit/pflag
```

---

Flags Usage
-----------

[](#flags-usage)

Flags - is an cli flags(options&amp;argument) parser and manager.

> example codes please see [example/flags-demo.php](example/flags-demo.php)

### Create Flags

[](#create-flags)

```
use Toolkit\PFlag\Flags;

require dirname(__DIR__) . '/test/bootstrap.php';

$flags = $_SERVER['argv'];
// NOTICE: must shift first element.
$scriptFile = array_shift($flags);

$fs = Flags::new();
// can with some config
$fs->setScriptFile($scriptFile);
/** @see Flags::$settings */
$fs->setSettings([
    'descNlOnOptLen' => 26
]);

// ...
```

### Define options

[](#define-options)

Examples for add flag option define:

```
use Toolkit\PFlag\Flag\Option;
use Toolkit\PFlag\FlagType;
use Toolkit\PFlag\Validator\EnumValidator;

// add options
// - quick add
$fs->addOpt('age', 'a', 'this is a int option', FlagType::INT);

// - use string rule
$fs->addOptByRule('name,n', 'string;this is a string option;true');

// - use array rule
/** @see Flags::DEFINE_ITEM for array rule */
$fs->addOptByRule('name-is-very-lang', [
    'type'   => FlagType::STRING,
    'desc'   => 'option name is to lang, desc will print on newline',
    'shorts' => ['d','e','f'],
    // TIP: add validator limit input value.
    'validator' => EnumValidator::new(['one', 'two', 'three']),
]);

// -- add multi option at once.
$fs->addOptsByRules([
    'tag,t' => 'strings;array option, allow set multi times',
    'f'     => 'bool;this is an bool option',
]);

// - use Option
$opt = Option::new('str1', "this is  string option, \ndesc has multi line, \nhaha...");
$opt->setDefault('defVal');
$fs->addOption($opt);
```

### Define Arguments

[](#define-arguments)

Examples for add flag argument define:

```
use Toolkit\PFlag\Flag\Argument;
use Toolkit\PFlag\FlagType;

// add arguments
// - quick add
$fs->addArg('strArg1', 'the is string arg and is required', 'string', true);

// - use string rule
$fs->addArgByRule('intArg2', 'int;this is a int arg and with default value;no;89');

// - use Argument object
$arg = Argument::new('arrArg');
// OR $arg->setType(FlagType::ARRAY);
$arg->setType(FlagType::STRINGS);
$arg->setDesc("this is an array arg,\n allow multi value,\n must define at last");

$fs->addArgument($arg);
```

### Parse Input

[](#parse-input)

```
use Toolkit\PFlag\Flags;
use Toolkit\PFlag\FlagType;

// ...

if (!$fs->parse($flags)) {
    // on render help
    return;
}

vdump($fs->getOpts(), $fs->getArgs());
```

**Show help**

```
$ php example/flags-demo.php --help
```

Output:

[![flags-demo](example/images/flags-demo.png)](example/images/flags-demo.png)

**Run demo:**

```
$ php example/flags-demo.php --name inhere --age 99 --tag go -t php -t java -d one -f arg0 80 arr0 arr1
```

Output:

```
# options
array(6) {
  ["str1"]=> string(6) "defVal"
  ["name"]=> string(6) "inhere"
  ["age"]=> int(99)
  ["tag"]=> array(3) {
    [0]=> string(2) "go"
    [1]=> string(3) "php"
    [2]=> string(4) "java"
  }
  ["name-is-very-lang"]=> string(3) "one"
  ["f"]=> bool(true)
}

# arguments
array(3) {
  [0]=> string(4) "arg0"
  [1]=> int(80)
  [2]=> array(2) {
    [0]=> string(4) "arr0"
    [1]=> string(4) "arr1"
  }
}

```

---

Get Value
---------

[](#get-value)

Get flag value is very simple, use method `getOpt(string $name)` `getArg($nameOrIndex)`.

> TIP: Will auto format input value by define type.

**Options**

```
$force = $fs->getOpt('f'); // bool(true)
$age  = $fs->getOpt('age'); // int(99)
$name = $fs->getOpt('name'); // string(inhere)
$tags = $fs->getOpt('tags'); // array{"php", "go", "java"}
```

**Arguments**

```
$arg0 = $fs->getArg(0); // string(arg0)
// get an array arg
$arrArg = $fs->getArg(1); // array{"arr0", "arr1"}
// get value by name
$arrArg = $fs->getArg('arrArg'); // array{"arr0", "arr1"}
```

---

Build simple cli app
--------------------

[](#build-simple-cli-app)

In the pflag, built in `CliApp` and `CliCmd` for quick create and run an simple console application.

### Create simple alone command

[](#create-simple-alone-command)

Build and run a simple command handler. see example file [example/clicmd.php](example/clicmd.php)

```
use Toolkit\Cli\Cli;
use Toolkit\PFlag\CliCmd;
use Toolkit\PFlag\FlagsParser;

CliCmd::new()
    ->config(function (CliCmd $cmd) {
        $cmd->name = 'demo';
        $cmd->desc = 'description for demo command';

        // config flags
        $cmd->options = [
            'age, a'  => 'int;the option age, is int',
            'name, n' => 'the option name, is string and required;true',
            'tags, t' => 'array;the option tags, is array',
        ];
        // or use property
        // $cmd->arguments = [...];
    })
    ->withArguments([
        'arg1' => 'this is arg1, is string'
    ])
    ->setHandler(function (FlagsParser $fs) {
        Cli::info('options:');
        vdump($fs->getOpts());
        Cli::info('arguments:');
        vdump($fs->getArgs());
    })
    ->run();
```

**Usage:**

```
# show help
php example/clicmd.php -h
# run command
php example/clicmd.php --age 23 --name inhere value1
```

- Display help:

[![cmd-demo-help](example/images/cli-cmd-help.png)](example/images/cli-cmd-help.png)

- Run command:

[![cmd-demo-run](example/images/cli-cmd-run.png)](example/images/cli-cmd-run.png)

### Create an multi commands app

[](#create-an-multi-commands-app)

Create an multi commands application, run subcommand. see example file [example/cliapp.php](example/cliapp.php)

```
use Toolkit\Cli\Cli;
use Toolkit\PFlag\CliApp;
use Toolkit\PFlag\FlagsParser;
use Toolkit\PFlagTest\Cases\DemoCmdHandler;

$app = new CliApp();

$app->add('test1', fn(FlagsParser $fs) => vdump($fs->getOpts()), [
    'desc'    => 'the test 1 command',
    'options' => [
        'opt1' => 'opt1 for command test1',
        'opt2' => 'int;opt2 for command test1',
    ],
]);

$app->add('test2', function (FlagsParser $fs) {
    Cli::info('options:');
    vdump($fs->getOpts());
    Cli::info('arguments:');
    vdump($fs->getArgs());
}, [
    // 'desc'    => 'the test2 command',
    'options' => [
        'opt1' => 'a string opt1 for command test2',
        'opt2' => 'int;a int opt2 for command test2',
    ],
    'arguments' => [
        'arg1' => 'required arg1 for command test2;true',
    ]
]);

// fn - required php 7.4+
$app->add('show-err', fn() => throw new RuntimeException('test show exception'));

$app->addHandler(DemoCmdHandler::class);

$app->run();
```

**Usage:**

```
# show help
php example/cliapp.php -h
# run command
php example/cliapp.php test2 --opt1 val1 --opt2 23 value1
```

- Display commands:

[![cli-app-help](example/images/cli-app-help.png)](example/images/cli-app-help.png)

- Command help:

[![cli-app-cmd-help](example/images/cli-app-cmd-help.png)](example/images/cli-app-cmd-help.png)

- Run command:

[![cli-app-cmd-run](example/images/cli-app-cmd-run.png)](example/images/cli-app-cmd-run.png)

---

Flag rule
---------

[](#flag-rule)

The options/arguments rules. Use rule can quick define an option or argument.

- string value is rule(`type;desc;required;default;shorts`).
- array is define item `SFlags::DEFINE_ITEM`
- supported type see `FlagType::*`

```
use Toolkit\PFlag\FlagType;

$rules = [
     // v: only value, as name and use default type FlagType::STRING
     // k-v: key is name, value can be string|array
     'long,s',
     // name => rule
     'long,a,b' => 'int', // long is option name, a and b is shorts.
     'f'      => FlagType::BOOL,
     'str1'   => ['type' => 'int', 'desc' => 'an string option'],
     'tags'   => 'array', // can also: ints, strings
     'name'   => 'type;the description message;required;default', // with desc, default, required
]
```

**For options**

- option allow set shorts

> TIP: name `long,a,b` - `long` is the option name. remaining `a,b` is short names.

**For arguments**

- argument no alias/shorts
- array value only allow defined at last

**Definition item**

The const `Flags::DEFINE_ITEM`:

```
public const DEFINE_ITEM = [
    'name'      => '',
    'desc'      => '',
    'type'      => FlagType::STRING,
    'helpType'  => '', // use for render help
    // 'index'    => 0, // only for argument
    'required'  => false,
    'default'   => null,
    'shorts'    => [], // only for option
    // value validator
    'validator' => null,
    // 'category' => null
];
```

---

Custom settings
---------------

[](#custom-settings)

### Settings for parse

[](#settings-for-parse)

```
    // -------------------- settings for parse option --------------------

    /**
     * Stop parse option on found first argument.
     *
     * - Useful for support multi commands. eg: `top --opt ... sub --opt ...`
     *
     * @var bool
     */
    protected $stopOnFistArg = true;

    /**
     * Skip on found undefined option.
     *
     * - FALSE will throw FlagException error.
     * - TRUE  will skip it and collect as raw arg, then continue parse next.
     *
     * @var bool
     */
    protected $skipOnUndefined = false;

    // -------------------- settings for parse argument --------------------

    /**
     * Whether auto bind remaining args after option parsed
     *
     * @var bool
     */
    protected $autoBindArgs = true;

    /**
     * Strict match args number.
     * if exist unbind args, will throw FlagException
     *
     * @var bool
     */
    protected $strictMatchArgs = false;
```

### Setting for render help

[](#setting-for-render-help)

support some settings for render help

```
    // -------------------- settings for built-in render help --------------------

    /**
     * Auto render help on provide '-h', '--help'
     *
     * @var bool
     */
    protected $autoRenderHelp = true;

    /**
     * Show flag data type on render help.
     *
     * if False:
     *
     * -o, --opt    Option desc
     *
     * if True:
     *
     * -o, --opt STRING   Option desc
     *
     * @var bool
     */
    protected $showTypeOnHelp = true;

    /**
     * Will call it on before print help message
     *
     * @var callable
     */
    private $beforePrintHelp;
```

- custom help message renderer

```
$fs->setHelpRenderer(function (\Toolkit\PFlag\FlagsParser $fs) {
    // render help messages
});
```

---

Unit tests
----------

[](#unit-tests)

```
phpunit --debug
```

test with coverage:

```
phpdbg -dauto_globals_jit=Off -qrr $(which phpunit) --coverage-text
phpdbg -dauto_globals_jit=Off -qrr $(which phpunit) --coverage-clover ./test/clover.info
# use xdebug
phpunit --coverage-clover ./test/clover.info
```

Project use
-----------

[](#project-use)

Check out these projects, which use  :

- [inhere/console](https://github.com/inhere/console) Full-featured php command line application library.
- [kite](https://github.com/inhere/kite) Kite is a tool for help development.
- More, please see [Packagist](https://packagist.org/packages/toolkit/pflag)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance61

Regular maintenance activity

Popularity37

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity65

Established project with proven stability

 Bus Factor1

Top contributor holds 93.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~66 days

Recently: every ~296 days

Total

21

Last Release

394d ago

Major Versions

v1.2.0 → v2.0.02021-12-09

PHP version history (3 changes)v1.0.0PHP &gt;7.1.0

1.x-devPHP &gt;7.2.0

v2.0.0PHP &gt;8.0.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/d23e1decaf354e8f36a7ad61128865dc78dd63336c2d023d79aa3ff8ba2a05ff?d=identicon)[inhere](/maintainers/inhere)

---

Top Contributors

[![inhere](https://avatars.githubusercontent.com/u/5302062?v=4)](https://github.com/inhere "inhere (118 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (8 commits)")

---

Tags

clicli-applicationcli-argumentscli-flagscli-optionscli-parsercommand-linecommand-line-appflag-parserflags

### Embed Badge

![Health badge](/badges/toolkit-pflag/health.svg)

```
[![Health](https://phpackages.com/badges/toolkit-pflag/health.svg)](https://phpackages.com/packages/toolkit-pflag)
```

###  Alternatives

[wp-cli/wp-cli

WP-CLI framework

5.1k17.2M320](/packages/wp-cli-wp-cli)[consolidation/annotated-command

Initialize Symfony Console commands from annotated command class methods.

22569.8M19](/packages/consolidation-annotated-command)[seld/cli-prompt

Allows you to prompt for user input on the command line, and optionally hide the characters they type

24725.8M17](/packages/seld-cli-prompt)[illuminate/console

The Illuminate Console package.

12944.1M5.1k](/packages/illuminate-console)[php-tui/php-tui

Comprehensive TUI library heavily influenced by Ratatui

589747.0k6](/packages/php-tui-php-tui)[codedungeon/php-cli-colors

Liven up you PHP Console Apps with standard colors

10210.1M26](/packages/codedungeon-php-cli-colors)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
