Lesson 6 / 10

Object-Oriented PHP: Classes and Objects

class Course {n    public string $title;n    private int $lessonCount;nn    public function __construct(string $title, int $lessonCount) {n        $this->title = $title;n        $this->lessonCount = $lessonCount;n    }nn    public function getTitle(): string {n        return $this->title;n    }n}nn$phpCourse = new Course("PHP", 10);necho $phpCourse->getTitle();   // PHP

__construct and $this

__construct runs automatically when you create a new object with new — the same idea as Python’s __init__ or Java’s constructor. $this refers to the specific object the method was called on, mirroring self in Python and the implicit this in Java or C++.

public vs private

Exactly like Java and C++, a private property can only be accessed from inside the class itself, forcing outside code to go through a public method like getTitle() instead of reaching in directly. This protects the object’s internal state from being set to something invalid from outside code.

Inheritance

class CertifiedCourse extends Course {n    private string $certificateName;nn    public function __construct(string $title, int $lessonCount, string $certificateName) {n        parent::__construct($title, $lessonCount);n        $this->certificateName = $certificateName;n    }n}

extends gives CertifiedCourse everything Course already has, plus its own additional property. parent::__construct(...) calls the parent class’s constructor, avoiding the need to repeat that shared setup logic.

Where this shows up

WordPress itself is full of classes built exactly this way — WP_Query, WP_Post, and every custom post type you register behind the scenes follow the same object-oriented pattern you just learned. Recognizing this pattern is genuinely useful the next time you look at WordPress core source code or a plugin.