PHP Tutorial · Object-Oriented PHP · Lesson 30 of 38
PHP Constructors
Initialise objects with __construct and constructor property promotion.
__construct
The constructor runs automatically when you call new. Use it to set up a valid object:
<?php
class User
{
private string $name;
private array $roles;
public function __construct(string $name, array $roles = ["member"])
{
$this->name = ucfirst($name);
$this->roles = $roles;
}
public function describe(): string
{
return $this->name . " (" . implode(", ", $this->roles) . ")";
}
}
echo (new User("ada"))->describe(), "\n";
echo (new User("lin", ["admin", "editor"]))->describe(), "\n";
Output
Ada (member) Lin (admin, editor)
Constructor property promotion (PHP 8)
Add a visibility keyword to a constructor parameter and PHP declares and assigns the property for you — far less boilerplate:
<?php
class Point
{
public function __construct(
public float $x = 0,
public float $y = 0,
) {}
public function distanceTo(Point $p): float
{
return sqrt(($p->x - $this->x) ** 2 + ($p->y - $this->y) ** 2);
}
public function __toString(): string
{
return "($this->x, $this->y)";
}
}
$a = new Point(3, 4);
echo "Point $a is ", $a->distanceTo(new Point()), " from the origin\n";
Output
Point (3, 4) is 5 from the origin
Other magic methods
__toString() defines how an object converts to a string; __get, __set and __call intercept access to undefined members (use sparingly).
Test yourself
What is the name of a PHP constructor method?
constructor__init____constructClass name
Show answer
Answer: __construct