Derived classes can override the values of inherited properties either by initializing them in the property declaration, or by setting their value in the constructor. The result is the same either way.
Is there a semantic difference, or any obvious advantage to either method?
Or is it just a matter of readability and personal preference?
Here is an (admittedly contrived) example to illustrate the two ways:
IdNumber
objects are specialized Number
objects. Among other differences, they set a specific default minimum value, where the parent class doesn't:
class Number
{
protected $value;
protected $minValue;
public function __construct ($value)
{
$this->value = $value;
}
public function setMinValue ($min)
{
$this->minValue = $min;
}
public function isValid ()
{
if (isset($this->minValue)) {
return $this->value >= $this->minValue;
} else {
return true;
}
}
}
class IdNumberA extends Number
{
protected $minValue = 1; //
/* ...plus more specialized methods... */
}
class IdNumberB extends Number
{
public function __construct ($value)
{
$this->minValue = 1;
parent::__construct($value);
}
/* ...plus more specialized methods... */
}