get_cli_args()
云策文档标注
概述
get_cli_args() 函数用于从命令行参数中获取指定参数的值。当参数被标记为必需但未设置时,函数会退出执行。
关键要点
- 函数接受两个参数:$param(字符串,必需)和 $required(布尔值,可选,默认 false)。
- 返回值为混合类型,表示参数的值或 null。
- 函数通过解析 $_SERVER['argv'] 数组来获取命令行参数。
- 如果 $required 为 true 且参数未设置,函数会触发退出。
代码示例
function get_cli_args( $param, $required = false ) {
$args = $_SERVER['argv'];
if ( ! is_array( $args ) ) {
$args = array();
}
$out = array();
$last_arg = null;
$return = null;
$il = count( $args );
for ( $i = 1, $il; $i < $il; $i++ ) {
if ( 0 === strpos( $args[$i], '--' ) ) {
$eq = strpos( $args[$i], '=' );
if ( $eq ) {
$out[ substr( $args[$i], 2, $eq - 2 ) ] = substr( $args[$i], $eq + 1 );
} else {
$key = substr( $args[$i], 2 );
if ( $i + 1 < $il && 0 !== strpos( $args[$i + 1], '--' ) ) {
$out[ $key ] = $args[$i + 1];
} else {
$out[ $key ] = true;
}
}
}
}
if ( isset( $out[ $param ] ) ) {
$return = $out[ $param ];
} elseif ( $required ) {
exit( 'Required parameter ' . $param . ' not set.' );
}
return $return;
}注意事项
- 函数假设命令行参数以 '--' 开头,例如 --param=value 或 --param value。
- 如果 $required 为 true 且参数缺失,会直接调用 exit() 终止脚本,需谨慎使用以避免意外退出。
- 函数仅处理从索引 1 开始的参数,忽略脚本名称(通常位于索引 0)。
原文内容
Returns value of command line params.
Description
Exits when a required param is not set.
Parameters
$paramstringrequired$requiredbooloptional-
Default:
false
Source
function get_cli_args( $param, $required = false ) {
$args = $_SERVER['argv'];
if ( ! is_array( $args ) ) {
$args = array();
}
$out = array();
$last_arg = null;
$return = null;
$il = count( $args );
for ( $i = 1, $il; $i < $il; $i++ ) {
if ( (bool) preg_match( '/^--(.+)/', $args[ $i ], $match ) ) {
$parts = explode( '=', $match[1] );
$key = preg_replace( '/[^a-z0-9]+/', '', $parts[0] );
if ( isset( $parts[1] ) ) {
$out[ $key ] = $parts[1];
} else {
$out[ $key ] = true;
}
$last_arg = $key;
} elseif ( (bool) preg_match( '/^-([a-zA-Z0-9]+)/', $args[ $i ], $match ) ) {
for ( $j = 0, $jl = strlen( $match[1] ); $j < $jl; $j++ ) {
$key = $match[1][ $j ];
$out[ $key ] = true;
}
$last_arg = $key;
} elseif ( null !== $last_arg ) {
$out[ $last_arg ] = $args[ $i ];
}
}
// Check array for specified param.
if ( isset( $out[ $param ] ) ) {
// Set return value.
$return = $out[ $param ];
}
// Check for missing required param.
if ( ! isset( $out[ $param ] ) && $required ) {
// Display message and exit.
echo ""$param" parameter is required but was not specifiedn";
exit;
}
return $return;
}