Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

post - PHP: $_GET and $_POST in functions?

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 independent 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 its job.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...