PHP:$ _GET和$ _POST函数? [英] PHP: $_GET and $_POST in functions?

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

问题描述

我被代码吓了一跳,其中诸如 $ _ GET ['username'] 等GET值不作为函数的参数。



您何时需要将POST和GET方法作为参数包含到函数中?

解决方案<

您何时需要将POST
和GET方法作为参数包含到
函数中?

我会说从不: $ _ GET $ _ POST 是什么被称为超全球变种:它们存在于整个剧本中;这意味着它们存在于函数/方法中。



特别是,你不需要 global 这些关键字。





尽管如此,依赖于你的函数/方法中的那些是一个相当糟糕的做法:你的函数/方法通常不应该依赖于任何未作为参数传递的东西。 / p>

我的意思是;考虑这两个函数:

$ p $ function check_login_password()
{
$ login = $ _GET ['login ];
$ password = $ _GET ['password'];
//使用$ login和$ password
}

p>

  / ** 
*检查登录名和密码
*
* @param $ login string
* @param $ password string
* @return boolean
* /
函数check_login_password($ login,$ password)
{
//使用$登录和$密码
}

好吧,第一个,你没有传递两个参数......但是这个函数不是独立的,并且在任何你不得不检查几个不是来自 $ _ GET



使用第二个函数,调用者负责传递正确的参数;这意味着它们可以来自任何你想要的地方:这个功能总是能够完成它的工作。


I am flabbergasted by the code, where the GET-values, such as $_GET['username'], are not included as parameters to functions.

When do you you need to include POST and GET methods as parameters to functions?

解决方案

When do you you need to include POST and GET methods as parameters to functions?

I would say "never" : $_GET and $_POST are what is called superglobals : they exists in the whole script ; which means they exist inside functions/methods.

Especially, you don't need to you the global keyword for those.


Still, relying on those in your functions/methods is quite a bad practice : your functions/methods should generally not depend on anything not passed as a parameter.

What I mean is ; consider those two functions :

function check_login_password()
{
    $login = $_GET['login'];
    $password = $_GET['password'];
    // Work with $login and $password
}

and

/**
 * Check login and password
 * 
 * @param $login string
 * @param $password string
 * @return boolean
 */
function check_login_password($login, $password)
{
    // Work with $login and $password
}

OK, with the first one, you don't have to pass two parameters... But that function will not be independant and will not work in any situation where you'd have to check a couple of login/password that doesn't come from $_GET.

With the second function, the caller is responsible for passing the right parameters ; which mean they can come from wherever you want : the function will always be able to do it's job.

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

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