For example is there a difference between the two? Is one preferred to the other?
Class Node{
public $parent = null;
public $right = null;
public $left = null;
function __construct($data){
$this->data = $data;
}
}
Class Node{
function __construct($data){
$this->data = $data;
$this->parent = null;
$this->left = null;
$this->right = null;
}
}
There are certain differences, yes:
#1: The class is not formally considered to have these properties if you only define them in the constructor
Example:
In addition to the different runtime behavior, it is bad form to use the constructor to “add” properties to your class. If you intend all objects of this class to have the property (which should be practically all of the time) then you should also formally declare them. The fact that PHP allows you to get away with this does not excuse the haphazard class design.
#2: You cannot initialize properties to non-constant values from outside the constructor
Example:
More examples regarding this constraint are provided in the PHP manual.
#3: For values initialized inside the constructor, if a derived class omits calling the parent constructor the result might be unexpected
Example: