作为Web开发人员,我总是将此方法用于登录表单或其他“保存”操作(忽略直接访问输入变量的危险):
- if (isset($_POST['action']) && $_POST['action'] == 'login')
- {
- // we're probably logging in,so let's process that here
- }
为了使这不那么乏味并且与DRY原则(有点)保持一致,我把它煮熟了:
- function isset_and_is ($superglobal,$key,$value)
- {
- $ref = '_' . strtoupper($superglobal);
- return isset($$ref[$key]) && $$ref[$key] == $value;
- }
- if (isset_and_is('post','action','login'))
- {
- // we're probably logging in,so let's process that here
- }
尽管我非常聪明地使用动态变量名来访问超全局,但这仍然很糟糕.
所以,我坚持使用这个丑陋的:
- function isset_and_is ($superglobal,$value)
- {
- switch (strtoupper($superglobal))
- {
- case 'GET': $ref =& $_GET; break;
- case 'POST': $ref =& $_POST; break;
- case 'REQUEST': $ref =& $_REQUEST; break;
- default: die('megafail'); return;
- }
- return isset($ref[$key]) && $ref[$key] == $value;
- }
- if (isset_and_is('post',so let's process that here
- }
我的问题:有没有办法动态访问超级全局变量,就像我试图在我的第二个代码示例中做的那样?如果不是,是否有更好/更有效的方法来完成我在第三个代码示例中所做的事情?
我的解决方案:感谢Tom Haigh’s answer,这是我将要使用的最终代码:
- function isset_and_is ($superglobal,$value)
- {
- $ref =& $GLOBALS['_' . strtoupper($superglobal)];
- return isset($ref[$key]) && $ref[$key] == $value;
- }
你可以这样做:
- function test($var) {
- //this
- var_dump( $GLOBALS[$var] );
- //or this
- global $$var; //this is needed even for superglobals
- var_dump($$var);
- }
- test('_GET');
所以你可以在你的情况下使用这样的东西
- function isset_and_is ($superglobal,$value) {
- $var = '_' . $superglobal;
- return isset($GLOBALS[$var]) && ($GLOBALS[$var][$key] == $value);
- }
- $is_login = isset_and_is('GET','login');
或者,您可以通过引用获取变量并使用isset(),例如
- function get_var(& $var) {
- if (isset($var)) {
- return $var;
- }
- return null;
- }
- //will not give you a notice if not set
- $post_var = get_var($_POST['var']);
- if (get_var($_GET['action']) == 'login') {
- //stuff
- }