PHP Constructors
A constructor is a special method automatically called when a new object is created from a class. In PHP, the constructor method is named __construct(), and it is typically used to set up initial values for an object's properties.
Constructors can accept parameters just like regular functions, allowing you to pass in initial data when creating an object, which avoids having to set each property manually afterward.
class MyClass {
function __construct($value) {
$this->property = $value;
}
}Defining a constructor
__construct() is defined inside a class like any other method, but PHP calls it automatically whenever new ClassName() is used.
Constructor property promotion
Since PHP 8, you can declare and assign properties directly in the constructor's parameter list, reducing boilerplate code.
<?php
class Person {
public $name;
function __construct($name) {
$this->name = $name;
}
}
$p = new Person("Amy");
echo $p->name;
?>AmyThe constructor sets the name property automatically when the object is created.
<?php
class Point {
public function __construct(public $x, public $y) { }
}
$p = new Point(3, 4);
echo "$p->x, $p->y";
?>3, 4Constructor property promotion declares and assigns $x and $y in a single step.
Key points
- __construct() runs automatically when an object is created.
- Constructors often initialize an object's properties.
- Constructors can accept parameters like regular functions.
- Constructor property promotion (PHP 8+) shortens property setup code.
