PHP 8 Intermediate OOP · 9 min read

PHP Classes, Constructors, and Property Promotion

Lesson 12 of 43 in the PHP 8 learning path.

How do I model a Student with a promoted constructor?

A Student is a small object with an id, a name, a track, and a score that has to stay inside 0 through 100. Constructor promotion writes those properties in the parameter list, so the class does not repeat each name as a property, a parameter, and an assignment. public readonly string $studentId can be read from outside the object and cannot be assigned again. The score is private readonly, so callers use score() and cannot replace it with an untyped public field.

The constructor throws InvalidArgumentException when the name is blank or the score is out of range. That means a Student value, once built, already satisfies the grade-book rule. PHP 8.3 adds typed class constants, and PASSING_LINE is a const int set to 75. isPassing() compares the private score with that constant. A later article can wrap this object in behavior that sends mail.

Syntax & Parameters

Syntax
public function __construct(
    public readonly string $studentId,
    public readonly string $name,
    public readonly string $track,
    private readonly int $score,
)

Example

src/Student.php
<?php

declare(strict_types=1);

final class Student
{
    public const int PASSING_LINE = 75;

    public function __construct(
        public readonly string $studentId,
        public readonly string $name,
        public readonly string $track,
        private readonly int $score,
    ) {
        if (trim($studentId) === '' || trim($name) === '' || trim($track) === '') {
            throw new InvalidArgumentException('Id, name, and track are required.');
        }
        if ($score < 0 || $score > 100) {
            throw new InvalidArgumentException('Score must be between 0 and 100.');
        }
    }

    public function score(): int
    {
        return $this->score;
    }

    public function isPassing(): bool
    {
        return $this->score >= self::PASSING_LINE;
    }
}

$student = new Student('2026-0142', 'Amina Cruz', 'web', 92);

echo 'name=' . $student->name . "\n";
echo 'id=' . $student->studentId . "\n";
echo 'track=' . $student->track . "\n";
echo 'score=' . $student->score() . "\n";
echo 'passing=' . ($student->isPassing() ? 'yes' : 'no') . "\n";

try {
    new Student('2026-0142', 'Amina Cruz', 'web', 140);
    echo "rejected=no\n";
} catch (InvalidArgumentException $error) {
    echo 'rejected=' . $error->getMessage() . "\n";
}

Expected Output

name=Amina Cruz
id=2026-0142
track=web
score=92
passing=yes
rejected=Score must be between 0 and 100.

Line-by-Line Walkthrough

  1. declare(strict_types=1) makes the new Student() calls in this file pass real strings and a real int.
  2. PASSING_LINE is a typed class constant, a PHP 8.3 feature, fixed at 75 for this grade book.
  3. The constructor promotes four properties: three public readonly fields and one private readonly score.
  4. trim() rejects a blank id, name, or track before the object exists.
  5. A score outside 0 through 100 throws InvalidArgumentException, so 140 never becomes a Student.
  6. score() returns the private int, which keeps direct writes off the property.
  7. isPassing() compares that int with self::PASSING_LINE.
  8. The successful object is Amina Cruz, id 2026-0142, track web, score 92.
  9. The echoes print those fields and passing=yes because 92 is at least 75.
  10. The second constructor call throws, and the catch prints the score validation message.

Common Pitfalls & Security

A class with public untyped properties is a loose record with extra syntax. Promotion saves lines and does not by itself validate anything. Readonly stops a later assignment. It does not stop a caller from passing a bad value into the constructor, so the checks have to live there. Names printed from public properties still need HTML encoding at the template.

  • A public writable score lets any page replace a grade after a careful constructor ran. Keep the score private readonly and expose score().
  • Readonly properties are written during construction. A second assignment is an error. Build a new Student when a corrected score is a real academic event.
  • Unsafe anti-pattern (do not ship): echo $student->name; in HTML. That is cross-site scripting (XSS) when the name contains markup. Escape at output.
  • A typed constant holds school policy such as the passing line. A per-student score stays a property.
  • final on the class blocks a subclass that weakens the constructor. Prefer composition when you need a mailer beside the student.
  • Catching the validation error and still inserting a row stores a student the constructor refused. Write the row only after new Student() returns.

Best Practices & Modern Standards

On PHP 8.3, promote constructor properties, mark them readonly when they should not change, and use typed constants for policy numbers such as the passing line. Keep the constructor as the only gate for blank names and impossible scores. A final class is a good default until a real extension point exists.

Return the object from a repository method once the row is valid. Templates read name and track and escape them. They do not assemble a student from raw request fields. That split keeps SQL and HTML out of the model and keeps the model free of a public bag of mixed data.

Real-World Use

The enrollment desk builds a Student after it has an id, a name, a track, and a placement score. Amina Cruz with score 92 becomes a passing student on the web track. A mistyped score of 140 is rejected before any roster line is saved. The passing line lives in one typed constant so every report uses 75 without a second copy of the number in the template.

Frequently Asked Questions

What does constructor promotion generate?

Each promoted parameter becomes a property and is assigned from the argument before the constructor body runs. The body can still reject a score of 140, as this class does.

Can callers change a readonly property later?

No. A readonly property is assigned during construction and then only read. score() exposes the private score without a setter.

Why is the score private while the name is public?

The name is a display value with no extra rule beyond being non-blank. The score has a range and a passing rule, so the class keeps the int private and answers through score() and isPassing().

What is a typed class constant?

PHP 8.3 lets you write public const int PASSING_LINE = 75. The type stops a later edit from assigning a string to a constant the rest of the class treats as an int.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…