Lesson 21 of 100
Classes12 min5 checksPHP 8.5

Constructors and Properties

Learn how __construct() sets up typed properties, how defaults and promotion shorten the code, and how public and private access protect object state.

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.

Example
<?php
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";
Output
[[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.

Example
<?php
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";
Output
["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.

Example
<?php
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"; }
Output
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 call new internally.
  • 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 name and quantity public, and unitCents private.
  • If the quantity is less than 1, the constructor stores 1 instead.
  • totalCents() returns the unit price times the stored quantity.
  • The function builds a CartLine and 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.

Before you start

Classes

You’ll practice
  • Initialize typed properties in a constructor
  • Understand public and private access
Your task

Make cartLine() pass all 5 checks. Run your code as often as you like, then check your answer.

exercise.phpSaved in this browserPHP 8.5
CONSOLE & CHECKS● Ready

Ready when you are

Your output will appear here.
Make it work. Then make it pass.

PHP loads on your first run. Each check starts fresh. Your code stays in this browser; clearing site data removes your progress. A check or the task looks wrong? Report a problem with this exercise.