I'm just new in learning OOP. I've read many articles so far and tried some tutorials. I just wonder why when declaring parameter on a constructor some values should be nulled.
function __construct($hostname = NULL, $username = NULL, $password = NULL, $database = NULL)
{
$this->hostname = !empty($hostname) ? $hostname : "";
$this->username = !empty($username) ? $username : "";
$this->password = !empty($password) ? $password : "";
$this->database = !empty($database) ? $database : "";
}
like this. I really want know.
Keeping argument as NULL would make the function run even if all the parameters are not passed during function call.
For example, if a function expects 3 arguments and you supplied only 2 and in function definition the third parameter is not assigned as NULL, the function will throw an error.
I just wonder why when declaring parameter on a constructor some values should be nulled.
These are NOT required to be nulled.
They are nulled as a default value for the parameter. For example for the function given by you in the example, can be called in one of the five ways:
One needs to be careful that it is not possible to call the function with $hostname, $password and let the function assume default value of $username.
This is a constructor with default values, If the parameters are not passed to _construct method it will assign the NULL values to the variables. So this means its not necessary to pass a parameters to this constructor.
This syntax is to facilitate you to initiate the class without passing any of the parameter
function __construct($hostname = NULL, $username = NULL, $password = NULL, $database = NULL)
this signature tells that you can optionally pass parameters suppose your Class A{}
has this constructor you can optionally initiate it in following ways
$t = new A();
$t1 = new A('locathost','user1','pw1', $db_connection);
$t2 = new A('localhost');
these all initializations will be valid.