01 · THE IDEAREAD → TRY → LEARN
Why objects need initialization
A class describes the shape of an object, but each new object still needs its own starting values. PHP calls the __construct() method on every object created with new, so the constructor is the natural place to set up state before anything else uses the object.
A constructor is an ordinary method with one special job. It can take any number of parameters. Those parameters can be required, typed, or given defaults. You pass the arguments in parentheses after the class name.
Typed properties set in a constructor
Properties can carry a type, such as int or string. A typed property with no default starts out uninitialized, and reading it before assignment throws an Error. The constructor is where you assign a value so that never happens.
class Point {
private int $x;
private int $y;
public function __construct(int $x, int $y = 0) {
$this->x = $x;
$this->y = $y;
}
public function toArray(): array { return [$this->x, $this->y]; }
}
$a = new Point(4, 5);
$b = new Point(4);
echo json_encode([$a->toArray(), $b->toArray()]) , "\n";[[4,5],[4,0]]
Inside a method, $this is the current object, and $this->x reads or writes its property. The second object omits $y, so it takes the default of 0.
Constructor promotion
Many constructors do nothing except copy parameters into properties. Since PHP 8.0 you can write a visibility modifier in front of a constructor parameter. PHP then declares a property of the same name and assigns the argument to it automatically. The body can stay empty, or contain extra statements that run after the assignments.
class Label {
public function __construct(public string $text, public int $size = 12, public bool $bold = false) {}
}
$label = new Label(bold: true, text: "Sale");
echo json_encode([$label->text, $label->size, $label->bold]), "\n";["Sale",12,true]
This example also uses named arguments. They let callers skip the middle default and pass values in any order. Promotion does not change how callers write new. You can mix promoted and ordinary parameters. A promoted parameter cannot be typed callable.
Public and private access
A public property can be read and written from anywhere. A private property is reachable only from code inside the same class. This lets a class keep its internal state safe and expose only the operations it wants, usually through methods.
class Account {
public function __construct(public string $owner, private int $balance) {}
public function balance(): int { return $this->balance; }
}
$account = new Account("Mina", 50);
echo $account->owner, "\n";
echo $account->balance(), "\n";
try { echo $account->balance; } catch (Error $e) { echo $e->getMessage(), "\n"; }Mina 50 Cannot access private property Account::$balance
Outside the class, the balance can be read only through balance(). Touching the private property directly throws an Error. Also note that the property and the method share the name balance; PHP keeps properties and methods separate.
Things to remember
- A class has only one constructor. If you need several ways to build an object, add static methods such as
fromJson()that callnewinternally. - A child class that defines its own constructor must call
parent::__construct()itself. PHP does not do it for you. - Always name the method
__construct(). A method named after the class has no special meaning in PHP 8. - Validation or normalization belongs in the constructor body. Then no object ever exists in an invalid state.
Exercise contract
Write the CartLine constructor and complete the function cartLine(string $name, int $unitCents, int $quantity): array.
- The class keeps
nameandquantitypublic, andunitCentsprivate. - If the quantity is less than 1, the constructor stores
1instead. totalCents()returns the unit price times the stored quantity.- The function builds a
CartLineand returns a list of three values: name, stored quantity, total in cents.
For example, cartLine("Pen", 150, 3) returns ["Pen", 3, 450], and cartLine("Tea", 250, 0) returns ["Tea", 1, 250]. Promotion keeps the constructor short, and the body only needs the clamping rule.
Recap
The constructor prepares a new object, typed properties catch wrong data early, promotion removes repetition, and private keeps state behind methods you control.
Classes
- Initialize typed properties in a constructor
- Understand public and private access