Lesson 11 โข Expert
Object-Oriented PHP ๐๏ธ
Organise your code with classes, objects, inheritance, interfaces, and PHP 8's constructor promotion โ the foundation of modern PHP.
What You'll Learn in This Lesson
- โข Classes, objects, constructors, and the $this keyword
- โข Access modifiers: public, protected, private
- โข Inheritance with extends and parent::
- โข Interfaces and abstract classes
- โข PHP 8 constructor promotion for cleaner code
Try It: Classes & Objects
Create classes with constructors, methods, static methods, and access modifiers
// PHP OOP: Classes & Objects (simulated in JavaScript)
console.log("=== Classes: The Blueprint ===");
console.log();
// PHP class with constructor, properties, methods
class User {
// In PHP: private string $name; private string $email;
constructor(name, email, role = "user") {
this.name = name; // PHP: $this->name = $name;
this.email = email;
this.role = role;
this.createdAt = new Date().toISOString().slice(0, 10);
}
getInfo() {
re
...Try It: Inheritance & Interfaces
Extend classes, implement interfaces, and use PHP 8 constructor promotion
// PHP OOP: Inheritance, Interfaces & Abstract Classes
console.log("=== Inheritance (extends) ===");
console.log();
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
speak() { return this.name + " says " + this.sound + "!"; }
toString() { return "[Animal: " + this.name + "]"; }
}
class Dog extends Animal {
constructor(name, breed) {
super(name, "Woof"); // PHP: parent::__construct($name, "Woof");
this.breed =
...โ ๏ธ Common Mistakes
๐ Quick Reference โ OOP
| Concept | Keyword | Purpose |
|---|---|---|
| Class | class Foo {} | Define a blueprint |
| Object | new Foo() | Create an instance |
| Inherit | extends | Build on existing class |
| Interface | implements | Enforce a contract |
| Abstract | abstract class | Base class (can't instantiate) |
| Static | Class::method() | Call without object |
๐ Lesson Complete!
You've mastered Object-Oriented PHP! Next, learn how to connect your PHP app to a MySQL database.
Sign up for free to track which lessons you've completed and get learning reminders.