$_GET 作为 PHP 函数中的参数 [英] $_GET as parameters in PHP functions

查看:26
本文介绍了$_GET 作为 PHP 函数中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有同样的问题,但是...我正在根据使用标头的 if 语句将用户重定向到通过函数构造的动态页面.要使该函数正常工作,它需要在标头的 GET 部分中传递参数.

I have the same question but...I'm redirecting the user depending on an if statement using headers to a dynamic page that is constructed through a function. For that function to work properly, it needs the parameters passed in the GET portion of the headers.

根据所提供的答案,这是一种不好的做法.我应该怎么做?

According to what to the answers provided, this is a bad practice. What way should I be doing it?

function page($title,$msg){
    $title = $_GET['title'];
    $msg = $_GET['msg'];
    echo '<h1>'.$title.'</h1>';

    echo '<p>';
    switch($msg){
        case 1:
            echo 'dwasdwadawdwadwa';
        break;
        case 2:
            echo 'wasdadwadwdad';
        break;
        default:
            echo 'wadasdasd';
        break;
    }
    echo '</p>';
}

ps:请随时指出您认为错误的任何其他内容.

ps: feel free to point out anything else you see wrong.

我发现了这个,但它并没有真正帮助我.

I found this but it doesn't really help me.

推荐答案

您链接的问题的答案表明函数不应依赖任何外部(例如全局)变量.$_GET$_POST(以及其他)是超级全局变量",这是 PHP 的一种语言特性,使它们可以在任何范围内使用.这意味着它们可能会在脚本中的任何地方意外修改.

The answer to the question you linked suggests that functions should not rely on any external (e.g. global) variables. $_GET and $_POST (amongst others) are 'super globals', a language feature of PHP that makes them available in any scope. This means they may be unexpectedly modified from anywhere in your scripts.

帮助避免这种情况的一种方法是避免在方法中使用超级全局变量,而是 - 正如另一个问题的答案所暗示的那样 - 改为要求您将从超级全局变量中获得的变量的参数.

One way to help avoid this is to avoid using super globals in methods and instead - as the answer to the other question suggests - is to instead require parameters for the variables you would otherwise get from the super globals.

例如,代替:

function add_user() {
  $user = $_GET['user'];
  // ...
}
add_user();

你会使用:

function add_user($user) {
  // ...
}
add_user($_GET['user']);

在您的情况下,您想要的是:

In your situation, what you would want is:

function page($title, $msg){
  echo '<h1>'.$title.'</h1>';
  echo '<p>';
  switch($msg){
    case 1:
      echo 'dwasdwadawdwadwa';
    break;
    case 2:
      echo 'wasdadwadwdad';
    break;
    default:
      echo 'wadasdasd';
    break;
  }
  echo '</p>';
}

然后,当你调用 page 时,你会调用它:

Then, when you call page you would call it as:

page($_GET['title'], $_GET['msg']);

这篇关于$_GET 作为 PHP 函数中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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