(PHP 4 >= 4.3.0, PHP 5, PHP 7)
getopt — コマンドライン引数のリストからオプションを取得する
$options
[, array $longopts
[, int &$optind
]] ) : arrayスクリプトに渡されたオプションをパースします。
optionslongoptsoptindoptind parameter is present, then the
index where argument parsing stopped will be written to this variable.
options パラメータに含まれる要素には次のようなものがあります。
注意: オプションの値で、" " (空白) を区切り文字として使用することはできません。
注意:
optionsとlongoptsの書式はほぼ同じです。唯一の違いは、longoptsはオプションの配列 (その各要素がオプションとなる) を受け取るけれどもoptionsは文字列 (その各文字がオプションとなる) を受け取るということです。
この関数はオプション/引数のペアを連想配列で返します。
失敗した場合に FALSE を返します。
注意:
オプション以外のものが見つかった時点でオプションのパースは終了し、 それ以降の内容は破棄されます。
| バージョン | 説明 |
|---|---|
| 7.1.0 |
optind パラメータが追加されました。
|
| 5.3.0 | "=" を引数/値の区切り文字として使用できるようになりました。 |
| 5.3.0 | オプションの値 ("::" で指定します) に対応しました。 |
| 5.3.0 |
パラメータ longopts
がすべてのプラットフォームで使えるようになりました。
|
| 5.3.0 | この関数はシステムに依存しなくなり、今では Windows でも動作するようになりました。 |
例1 getopt() の例:基本編
<?php
// スクリプト example.php
$options = getopt("f:hp:");
var_dump($options);
?>
shell> php example.php -fvalue -h
上の例の出力は以下となります。
array(2) {
["f"]=>
string(5) "value"
["h"]=>
bool(false)
}
例2 getopt() の例:長いオプション
<?php
// スクリプト example.php
$shortopts = "";
$shortopts .= "f:"; // 値が必須
$shortopts .= "v::"; // 値がオプション
$shortopts .= "abc"; // これらのオプションは値を受け取りません
$longopts = array(
"required:", // 値が必須
"optional::", // 値がオプション
"option", // 値なし
"opt", // 値なし
);
$options = getopt($shortopts, $longopts);
var_dump($options);
?>
shell> php example.php -f "value for f" -v -a --required value --optional="optional value" --option
上の例の出力は以下となります。
array(6) {
["f"]=>
string(11) "value for f"
["v"]=>
bool(false)
["a"]=>
bool(false)
["required"]=>
string(5) "value"
["optional"]=>
string(14) "optional value"
["option"]=>
bool(false)
}
例3 getopt() の例:複数のオプションを一度に渡す
<?php
// スクリプト example.php
$options = getopt("abc");
var_dump($options);
?>
shell> php example.php -aaac
上の例の出力は以下となります。
array(2) {
["a"]=>
array(3) {
[0]=>
bool(false)
[1]=>
bool(false)
[2]=>
bool(false)
}
["c"]=>
bool(false)
}
例4 getopt() example: Using optind
<?php
// Script example.php
$optind = null;
$opts = getopt('a:b:', [], $optind);
$pos_args = array_slice($argv, $optind);
var_dump($pos_args);
shell> php example.php -a 1 -b 2 -- test
上の例の出力は以下となります。
array(1) {
[0]=>
string(4) "test"
}