Lesson 14 — Object-Oriented PHP
OOP: Classes and Objects
PHP fully supports object-oriented programming, letting you group related data and behaviour into classes, just as in languages like Java or C++.
Defining a Class
A PHP class groups properties (variables) and methods (functions) together, with the special __construct method running automatically whenever a new object is created.
PHP — A simple class
class Student {
public string $name;
public int $age;
public function __construct(string $name, int $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce(): string {
return "Hi, I'm {$this->name}, age {$this->age}";
}
}
$s1 = new Student("Thandeka", 21);
echo $s1->introduce();
Common Mistakes
- Forgetting the $this-> prefix when accessing a property or method from within the class itself.
- Using -> to access properties/methods when => (array syntax) was intended, or vice versa.
- Not declaring property visibility (public/private/protected), leaving intent unclear.
- Forgetting the new keyword when creating an object from a class.
Professional Tip
Use $this->propertyName to access an object's own properties and methods from inside its class definition — forgetting $this is one of the most common early PHP OOP mistakes.
Your Turn
Create a Book class with title, author, and price properties, a constructor to set them, and a method that returns a formatted description string.
Mini Quiz
Which special method runs automatically whenever a new object is created from a PHP class?
PHP's
__construct magic method runs automatically at the moment an object is instantiated with new, making it the natural place to set up initial property values.