php – 有没有办法动态访问超全局?

前端之家收集整理的这篇文章主要介绍了php – 有没有办法动态访问超全局?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
作为Web开发人员,我总是将此方法用于登录表单或其他“保存”操作(忽略直接访问输入变量的危险):
  1. if (isset($_POST['action']) && $_POST['action'] == 'login')
  2. {
  3. // we're probably logging in,so let's process that here
  4. }

为了使这不那么乏味并且与DRY原则(有点)保持一致,我把它煮熟了:

  1. function isset_and_is ($superglobal,$key,$value)
  2. {
  3. $ref = '_' . strtoupper($superglobal);
  4.  
  5. return isset($$ref[$key]) && $$ref[$key] == $value;
  6. }
  7.  
  8. if (isset_and_is('post','action','login'))
  9. {
  10. // we're probably logging in,so let's process that here
  11. }

尽管我非常聪明地使用动态变量名来访问超全局,但这仍然很糟糕.

所以,我坚持使用这个丑陋的:

  1. function isset_and_is ($superglobal,$value)
  2. {
  3. switch (strtoupper($superglobal))
  4. {
  5. case 'GET': $ref =& $_GET; break;
  6. case 'POST': $ref =& $_POST; break;
  7. case 'REQUEST': $ref =& $_REQUEST; break;
  8. default: die('megafail'); return;
  9. }
  10.  
  11. return isset($ref[$key]) && $ref[$key] == $value;
  12. }
  13.  
  14. if (isset_and_is('post',so let's process that here
  15. }

我的问题:有没有办法动态访问超级全局变量,就像我试图在我的第二个代码示例中做的那样?如果不是,是否有更好/更有效的方法来完成我在第三个代码示例中所做的事情?

我的解决方案:感谢Tom Haigh’s answer,这是我将要使用的最终代码

  1. function isset_and_is ($superglobal,$value)
  2. {
  3. $ref =& $GLOBALS['_' . strtoupper($superglobal)];
  4.  
  5. return isset($ref[$key]) && $ref[$key] == $value;
  6. }
你可以这样做:
  1. function test($var) {
  2. //this
  3. var_dump( $GLOBALS[$var] );
  4.  
  5. //or this
  6. global $$var; //this is needed even for superglobals
  7. var_dump($$var);
  8. }
  9.  
  10. test('_GET');

所以你可以在你的情况下使用这样的东西

  1. function isset_and_is ($superglobal,$value) {
  2. $var = '_' . $superglobal;
  3. return isset($GLOBALS[$var]) && ($GLOBALS[$var][$key] == $value);
  4. }
  5.  
  6. $is_login = isset_and_is('GET','login');

或者,您可以通过引用获取变量并使用isset(),例如

  1. function get_var(& $var) {
  2. if (isset($var)) {
  3. return $var;
  4. }
  5. return null;
  6. }
  7.  
  8. //will not give you a notice if not set
  9. $post_var = get_var($_POST['var']);
  10.  
  11. if (get_var($_GET['action']) == 'login') {
  12. //stuff
  13. }

猜你在找的PHP相关文章