Constructor¶
The constructor is a magic method in a class, which is called at instantiation of an object, with the provided arguments. It is called __construct.
The constructor is an optional method: a class may be created without it. Though, it is very common to have it.
In PHP, parent’s constructor are not automatically called, when a child class defines a constructor. They have to be called explicitly.
When a class has a parent, with a constructor, and not constructor itself, then the parent constructor is automatically called, by inheritance.
A constructor may have a visibility, and be not available to the outside. In particular, when creating named constructors, the magic method __construct is usually made private and object instantiation happens in a static method of that same class.
<?php
class X {
private $property;
function __construct($value) {
$this->property = $value;
}
}
$x = new X(1);
?>
See also What and Why We Should Use PHP Constructors and PHP OOP Constructor: How It Works in a Class with Examples.
Related : Destructor, Inheritance, Visibility, Named Constructors, Autowiring, instance, Promoted Properties