Reputation: 26
Hello I'm watching a tutorial about OOP PHP "How to make login form". And I can't understand how the form post was gotten from this code.
input.php
class input
{
public static function exists($type = 'post')
{
switch ($type)
{
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
}
register.php
if (input::exists())
{
//the submit button was clicked
}
So I will be happy if someone explain how does that work and how can i specify it to a specific form. Like this.
if ($_POST['specific submit name'])
{
// the specific submit button was clicked.
}
Upvotes: 1
Views: 731
Reputation: 5141
This function:
public static function exists($type = 'post')
{
switch ($type)
{
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
checks if the $_POST
or $_GET
superglobal arrays are empty. So let's say that you need to check if a POST requests has reached your page. You call input::exists('post');
That means the first case is true and this part of the code will be executed:
return (!empty($_POST)) ? true : false;
This code returns true
if $_POST
is not empty, which practically means there's data in it or false
if it is empty. Truth be told, this statement could be more easily written like this:
return !empty($_POST);
The if/else logic is pretty reduntant as is most of that code. To check if a particular value is in the $_POST
array you can use isset
.
So let's say you submit a form or send an AJAX request and one of the fields has a name of 'foo', you can check if 'foo' exists in $_POST
like this:
if(isset($_POST['foo'])
{
//do something with foo
}
As you can see there are simpler ways to check if $_POST
is populated and with what values. As I said above I consider the input
class and the exists
method reduntant code. You could use this tutorial just for learning what OOP is but I wouldn't rely on it
Upvotes: 1