Python Classes, Objects & Constructor Property Promotion
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.
"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", "alice@zen.com");Use constructor promotion to declare and assign class properties directly in __construct.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
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.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Create a ServerNode Class
Create a class ServerNode with promoted properties public string $host and public int $port = 8080.
Add a method getEndpoint(): string returning "$this->host:$this->port".
In main, instantiate $node = new ServerNode("api.zencompiler.com", 9000).
Print "Endpoint: " followed by $node->getEndpoint().
Finished reading and practicing?
Mark this lesson as completed to update your course progress.