如何通过命令行参数一起访问argv和选项在php [英] how can access argv and options together in php through command line arguments

查看:125
本文介绍了如何通过命令行参数一起访问argv和选项在php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有许多php脚本运行在活的服务器上,使用命令行的参数。
现在我需要在这些cron中添加一个参数,这将告诉我关于环境,这反过来选择服务器(从,主)。此选择的服务器是一个中心库代码。

we have many php scripts running on live servers which use arguments from command line. Now i need to add one more argument in some of these crons which will tell me about the environment, which in turn select the server (slave, master). ANd this selection of servers is a central library code.

我不想更改当前脚本中访问的参数。
所以只有选项是在结尾添加这个新的环境参数。但在这种情况下,有crons不会包含这个环境参数。所以我不能盲目地访问库中的最后一个参数。
所以我想为这个使用选项。

I dont want to change argument accessed in current scripts. so only option is to add this new environment argument at the end. But in that case there are crons which wont be containing this environment arguments. So i cannot blindly access the last argument in the library. So i thought to use options for this.

所以我的脚本将运行在终端像
php myscript.php arg1 arg2 -env slave

so my script will be run in terminal like php myscript.php arg1 arg2 -env slave

但在这种情况下,我无法获取php中的选项。可能是因为它混合了直接提供的参数和选项..

but in this case i cannot get options in php .May be because it mix of arguments supplied directly and with options..

该怎么办?任何帮助?

what to do? Any help?

推荐答案

首先搜索数组中的选项( -env argv 从数组( $ argv )获取并增加1以获取选项的值:

First search for the option(-env) in the array of argv get the key from array($argv) and increment by 1 to get the value of the option:

if (false !== $key = array_search('-env', $argv)) {
    $value = $key+1;
    $env = $argv[$value]; // $env will be 'slave' now.
} else {
    // do something else
} 

可能有更好的选项。

参考 PHP如果in_array()如何获取密钥? hehe!

这篇关于如何通过命令行参数一起访问argv和选项在php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆