PHP Constructors
A constructor — __construct — runs when an instance is created. Use it to set up state. PHP allows exactly one constructor per class.
Classic form
PHP
class Account {
public string $owner;
public float $balance;
public function __construct(string $owner, float $balance = 0) {
$this->owner = $owner;
$this->balance = $balance;
}
}
$a = new Account('Ada', 100);
Promoted form (8.0+)
PHP
class Account {
public function __construct(
public string $owner,
public float $balance = 0,
) {}
}
Named arguments
Construct with named arguments for clarity:
PHP
$a = new Account(owner: 'Ada', balance: 1_000);
Calling the parent constructor
PHP
class SavingsAccount extends Account {
public function __construct(
string $owner,
float $balance,
public float $interestRate,
) {
parent::__construct($owner, $balance);
}
}
Static factories
Sometimes you want multiple ways to build an instance. Add named static methods:
PHP
class Money {
private function __construct(public readonly int $cents) {}
public static function fromCents(int $c): self { return new self($c); }
public static function fromDollars(float $d): self { return new self((int) round($d * 100)); }
}
$a = Money::fromCents(1000);
$b = Money::fromDollars(9.99);
Tip: Keep constructors fast and free of side effects. No DB queries, no API calls, no logging. They should set state, not do things.
Example
Example
<?php
class Account {
public function __construct(
public string $owner,
public float $balance = 0,
) {}
}
$a = new Account('Ada', 100);
print_r($a);
Try it Yourself »
Exercise
PHP's constructor method name.
public function
(string $name) {}
Double-underscore + construct.
Discussion
Loading…