9

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hhh
  • 50,788
  • 62
  • 179
  • 282
  • 3
    What is your real question? The only sentence (although flawed) with a question mark at the end does not make any sense. $_GET and $_POST are global, they can be used anywhere. Is it good coding practice, maybe, maybe not. – X-Istence Aug 30 '09 at 19:25

3 Answers3

30

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
1

$_GET and $_POST are global variables. They have values, not methods.

It is their values you want to send to functions, and classes/functions should generally be unaware of anything outside them, like where the data comes from. Many use the shortcut of using the global variables in functions, and thus limiting the usability of their functions.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
OIS
  • 9,833
  • 3
  • 32
  • 41
  • To be fair, it may refer the ***HTTP*** *methods* [GET](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) and [POST](http://en.wikipedia.org/wiki/POST_%28HTTP%29) (though the question is confusing). – Peter Mortensen Oct 29 '19 at 15:44
0

You don't need to send them as function parameters as they are global variables (accessible everywhere in the code).

But it's always a good practice to filter and validate them before you use them in your code.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rogeriopvl
  • 51,659
  • 8
  • 55
  • 58