How to write a constructor method without risking an error?
When we try to create an object that has a constructor method, we run the risk of our code breaking if we don’t pass a value to the constructor. In order to avoid this risk, we can define a default value for the properties that we would like to set through the constructor. The default value may be the most reasonable choice for the property, zero, an empty string, or even a null.
If we use a null as the default value, we can use a condition to assess if a value was passed and then, only in that case, assign the value to the property.
In the example below, we give a default value of null to the $model property and, only if a value is passed to the constructor, we assign this value to the property. In any other case, the $model property has a default value of "N/A" string.
class Car {
// The $model property has a default value of "N/A"
private $model = "N/A";
// We don’t have to assign a value to the $model property
//since it already has a default value
public function __construct($model = null)
{
// Only if the model value is passed it will be assigned
if($model)
{
$this -> model = $model;
}
}
public function getCarModel()
{
return ' The car model is: ' . $this -> model;
}
}
//We create the new Car object without passing a value to the model
$car1 = new Car();
echo $car1 -> getCarModel();
Even though we created the object without passing a value to the model property, we didn't cause an error because the model property in the constructor has a default value of null.
Result:
The car model is: N/A
On the other hand, let’s see what happens when we define the model once we create the object. In the example, we assign the value "Merceds" to the $model property as soon as we create the object.
class Car {
private $model = '';
//__construct
public function __construct($model = null)
{
if($model)
{
$this -> model = $model;
}
}
public function getCarModel()
{
return ' The car model is: ' . $this -> model;
}
}
//We create the new Car object with the value of the model
$car1 = new Car('Mercedes');
echo $car1 -> getCarModel();
Result:
The car model is: Mercedes