Coding/Learn/php/php classes objects constructors
PHP Foundational Course
01.Introduction, Server-Side Architecture & Syntax
02.Variables, Strict Types & Dynamic Casting
03.Strings, Numbers & Built-in Math Functions
04.Operators, Null Coalescing & Magic Constants
05.Control Flow: If-Else, Switch & Modern Match Expressions
06.Loops: While, For & Foreach Traversal
07.Functions, Type Declarations & Named Arguments
08.Arrays & Functional Array Manipulation
09.Superglobals, Form Handling & Input Sanitization
10.Date, Time & DateTimeImmutable Objects
11.File System, Streams & I/O Operations
12.Cookies, Sessions & State Management
13.Exceptions, Throwables & Custom Error Fences
14.Classes, Objects & Constructor Property Promotion
15.Inheritance, Access Modifiers & Method Overriding
16.Interfaces, Abstract Classes & Polymorphism
17.Traits, Static Members & Namespaces
18.PDO, MySQL & Prepared Statements against SQL Injection
19.JSON & XML REST API Interoperability
20.Capstone: Production Secure Backend API & User Registry Engine
Course Certificate0%

Complete all lessons to earn

LearnClasses, Objects & Constructor Property Promotion
14 / 20 0%
Lesson 14 of 20
9 mins read

Classes, Objects & Constructor Property Promotion

PreviousNext Lesson
In Plain English

PHP features a complete, modern Object-Oriented Programming (OOP) model. Learn class definitions, instantiation ($obj = new ClassName()), methods ($this->method()), destructors (__destruct), and PHP 8 constructor property promotion for zero-boilerplate field assignments.

The Mental Model

"A class is an architectural blueprint for a drone. An object is the physical drone built from that blueprint. Constructor promotion is an automated assembly line that installs the camera and battery instantly without tedious manual wiring."

Deep Dive: How It Works

Classes & Instances: class User { ... } defines state and behavior; $user = new User(...) instantiates.

$this Reference: References the active instance context inside member methods ($this->name).

PHP 8 Constructor Promotion: public function __construct(public string $name, public int $age) {} declares and assigns properties automatically in the parameter list.

Destructor: __destruct() executes automatically when an object loses all references or script terminates.

Syntax Blueprint

<?php

class User {
    public function __construct(
        public string $name,
        public string $email
    ) {}
}

$u = new User("Alice", "[email protected]");

Use constructor promotion to declare and assign class properties directly in __construct.

PointCore Rules to Remember

Point star
Zero Boilerplate: Constructor promotion eliminates manual property declarations and $this->x = $x assignments.
Point star
Object Operator (->): Access properties and invoke methods using the single arrow -> operator ($user->getName()).
Point star
Readonly Properties (PHP 8.1): public readonly string $id prevents modification after initialization.

Common Beginner Traps & How to Fix Them

Mistake:Using $this->$property instead of $this->property.

Why it happens: Adding the extra $ attempts dynamic variable-property evaluation, leading to undefined property notices.

How to fix: Omit the dollar sign after the object operator: $this->property.

Pro Tip: Mark entire classes as readonly (readonly class UserDto {}) in PHP 8.2+ to enforce immutability across all properties.

Live Interactive Example

Hit Run Code to see it live
Constructor Promotion & Method Invocation
PHP 8.2 / CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Output Console
Click "Run Code" to view the rendered output.
How it works: Constructor promotion created and populated title, price, and default stock properties.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Create a ServerNode Class

  • PointCreate a class ServerNode with promoted properties public string $host and public int $port = 8080.
  • PointAdd a method getEndpoint(): string returning "$this->host:$this->port".
  • PointIn main, instantiate $node = new ServerNode("api.zencompiler.com", 9000).
  • PointPrint "Endpoint: " followed by $node->getEndpoint().
1
2
3
4
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates