TExcelTAD
Home › PHP › PHP Constructor

PHP Constructor

A constructor is a special method that PHP calls automatically when you create an object with new. Its job is to put the new object into a valid starting state, so you never have a half-built object lying around.

In PHP the constructor is always named __construct (two underscores).

A basic constructor

php · try it yourself
<?php
class Player {
    public string $name;
    public int $score;

    public function __construct(string $name, int $score = 0) {
        $this->name = $name;
        $this->score = $score;
        echo "Created player {$name}\n";
    }
}

$p1 = new Player('Mai');
$p2 = new Player('Kenji', 40);

echo "{$p1->name}: {$p1->score}\n";
echo "{$p2->name}: {$p2->score}\n";
Created player Mai
Created player Kenji
Mai: 0
Kenji: 40

The arguments you pass to new Player(...) go straight to __construct. Default parameter values work just like in ordinary functions.

Constructor property promotion

Declaring a property, accepting a parameter and assigning one to the other is so common that PHP 8.0 added a shortcut. Put a visibility keyword (public, protected, private) — and optionally readonly — in front of a constructor parameter, and PHP declares and assigns the property for you:

php · try it yourself
<?php
class Product {
    public function __construct(
        public string $name,
        public float $price,
        private int $stock = 0,
    ) {}

    public function label(): string {
        return sprintf('%s - $%.2f (%d in stock)', $this->name, $this->price, $this->stock);
    }
}

$tea = new Product('Green tea', 4.5, 12);
$mug = new Product('Mug', 9.99);

echo $tea->label() . "\n";
echo $mug->label() . "\n";
Green tea - $4.50 (12 in stock)
Mug - $9.99 (0 in stock)

The empty body {} is fine: all the work happens in the parameter list. You can still put extra statements in the body and mix promoted and normal parameters.

Classic style Promoted style
declare private int $stock; —
parameter int $stock parameter private int $stock
$this->stock = $stock; in the body —

Validating input

Because the constructor runs before anyone can use the object, it is the perfect place to reject bad data. Throwing an exception from the constructor means the object is never created:

php · try it yourself
<?php
class Temperature {
    public function __construct(public readonly float $celsius) {
        if ($celsius < -273.15) {
            throw new InvalidArgumentException("Below absolute zero: {$celsius}");
        }
    }

    public function fahrenheit(): float {
        return $this->celsius * 9 / 5 + 32;
    }
}

foreach ([21.5, -300] as $value) {
    try {
        $t = new Temperature($value);
        echo "{$t->celsius} C = {$t->fahrenheit()} F\n";
    } catch (InvalidArgumentException $e) {
        echo "Rejected: " . $e->getMessage() . "\n";
    }
}
21.5 C = 70.7 F
Rejected: Below absolute zero: -300

Named arguments

With several parameters it is easy to mix up the order. Named arguments (PHP 8.0) let you pass values by parameter name, in any order, and skip optional ones:

php · try it yourself
<?php
class Email {
    public function __construct(
        public string $to,
        public string $subject = '(no subject)',
        public bool $urgent = false,
    ) {}
}

$e = new Email(urgent: true, to: 'ana@example.com');
echo "To: {$e->to}\n";
echo "Subject: {$e->subject}\n";
echo "Urgent: " . ($e->urgent ? 'yes' : 'no') . "\n";
To: ana@example.com
Subject: (no subject)
Urgent: yes

Static factory methods

Sometimes there are several sensible ways to build an object. Instead of a constructor with many optional flags, add named constructors — static methods that call new for you:

php
class Money {
    private function __construct(public int $cents) {}

    public static function fromDollars(float $d): static { return new static((int) round($d * 100)); }
    public static function fromCents(int $c): static { return new static($c); }
}

$a = Money::fromDollars(2.5);   // 250 cents

Making the constructor private forces everyone to use the factory methods.

Tip: Keep constructors simple: assign and validate. Avoid slow work such as database queries or HTTP calls in a constructor — it makes objects hard to create in tests.

Test yourself

What is the name of a PHP constructor method?

  1. The class name
  2. constructor
  3. __construct
  4. __init__

What does public function __construct(private int $id) {} do?

  1. Nothing; the body is empty
  2. Declares a private $id property and assigns the argument to it
  3. Creates a static property
  4. Throws an error because the body is empty

What happens if a constructor throws an exception?

  1. The object is created with default values
  2. The object is not created and the exception propagates to the new expression
  3. PHP silently ignores it
  4. The destructor runs first and then the object is returned