Oop
By the end of this lesson you'll be able to model real things as classes — bundling their data and behaviour into objects with constructors, visibility, static members, constants, and readonly properties — the foundation of every modern PHP application.
Part of the free Php course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
1️⃣ Classes, Properties & Objects
Up to now your data has lived in loose variables. Object-oriented programming (OOP) bundles related data and the code that works on it into one unit. A class is the blueprint: it lists the properties (the data each object holds) and the methods (the things it can do). An object is a single thing built from that blueprint with the new keyword. You reach inside an object with the arrow operator - > . Typing each property ( string $name ) tells PHP — and your editor — exactly what kind of value belongs there.
Notice $rex and $buddy are completely separate — each carries its own name and age . That independence is the whole point: one blueprint, many self-contained objects.
2️⃣ The Constructor, $this & Methods
Setting every property by hand is tedious. A constructor — the special method named __construct() — runs automatically the instant you write new , so an object is born ready to use. Inside any method, $this means "this particular object", so $this- > name = $name stores the passed-in value on the object. A method is just a function that lives in the class and can use $this .
3️⃣ Visibility & Constructor Promotion
Each property has a visibility that decides who may touch it. public means anyone, anywhere; private means only code inside the same class ; protected is like private but also visible to classes that extend it. Hiding data behind private lets a class guarantee it stays valid — outsiders go through methods (a getter like getBalance() ) instead of poking the value directly. PHP 8's constructor property promotion declares the property and assigns the argument in one move: put the visibility keyword right in the constructor's parameter list and PHP does the $this- > x = $x for you.
The whole class is just a constructor and two short methods, yet $balance can never be set to a nonsense value from outside — that's encapsulation , the real payoff of private .
4️⃣ Static Members & Class Constants
Most properties belong to an object . A static property or method belongs to the class itself — there's one shared copy and you reach it with Class::member , no new needed. From inside the class you write self:: to mean "this class" ( static:: is its close cousin that respects subclasses — handy once you use inheritance). A class constant ( const MAX = 100; ) is a fixed value attached to the class that can never change, written in UPPER_CASE by convention.
Now you try. The class below is almost complete — fill in each ___ using the 👉 hint, then run it and check it against the Output panel.
One more — this time the blanks are about static members. Fill them in so the shared counter works.
5️⃣ Readonly Properties
Some values should be set once and then frozen — an id , a created-at timestamp, a primary key. PHP 8.1's readonly keyword does exactly that: the property can be assigned a single time (almost always inside the constructor) and any later attempt to change it throws an error. It pairs perfectly with constructor promotion, giving you tamper-proof objects with almost no code.
Common Errors (and the fix)
- "Cannot access private property User::$balance" — you tried to read or write a private property from outside the class (e.g. $acc- > balance ). Private means in-class only. Add a public method — a getter like getBalance() — and call that instead.
- "Undefined variable $name" inside a method — you forgot $this- > . A bare $name is a local variable; the property is $this- > name . Inside any non-static method, reach properties through $this .
- "Using $this when not in object context" — you used $this inside a static method. Static methods belong to the class, not an object, so there's no $this . Use self:: for static members, or make the method non-static if it needs object data.
- "Too few arguments to function __construct(), 0 passed" — you wrote new Dog() but the constructor requires arguments. Pass them: new Dog("Rex", 3) , or give the parameters defaults ( int $age = 0 ).
- "Cannot modify readonly property User::$id" — you tried to reassign a readonly property after it was first set. That's the whole point of readonly: set it once in the constructor and never again. If it must change, don't mark it readonly.
Pro Tips
- 💡 Start private , widen only when needed. It's easy to make a property more visible later; locking down a public property others already use is painful.
- 💡 Reach for constructor promotion by default. It removes the declare-then-assign boilerplate and is the modern, idiomatic style.
- 💡 Use constants and readonly for "facts that never change." They document intent and let PHP catch accidental edits for you.
📋 Quick Reference — PHP OOP
Syntax
Example
What It Does
class
class Dog { }
Define a blueprint
new
new Dog("Rex", 3)
Build an object (instance)
public/private/protected
private int $age;
Set who can access a property
__construct
function __construct(...)
Runs automatically on new
$this- >
$this- > name
This object's property/method
static + self::
self::$count
Class-level data, one shared copy
const
const MAX = 100;
A fixed value on the class
readonly
readonly int $id
Set once, then locked
Frequently Asked Questions
Mini-Challenge: Rectangle Class
No code is filled in this time — just a brief and an outline. Write the class yourself, run it on onecompiler.com/php or your own machine, then check your result against the expected output in the comments. This is exactly the write-run-check loop you'll use on every real class.
🎉 Lesson Complete!
- ✅ A class is a blueprint; new builds independent objects from it
- ✅ Typed properties with public / private / protected control who can touch each value
- ✅ __construct() runs on new , and $this refers to the current object inside methods
- ✅ Constructor promotion declares and assigns a property in one line
- ✅ static members + self:: / static:: live on the class; const and readonly lock values down
- ✅ Next lesson: Database Integration — connect your classes to a MySQL database and store objects for real
Practice quiz
What is the relationship between a class and an object?
- They are the same thing
- An object is a blueprint for a class
- A class is a blueprint; an object is built from it
- A class is one instance of an object
Answer: A class is a blueprint; an object is built from it. A class is the blueprint, and each object (instance) is a thing built from it with new.
Which keyword builds an object from a class?
- new
- create
- build
- make
Answer: new. new builds an object (instance) from a class, e.g. new Dog().
Which operator reaches a property or method on an object?
- ::
- .
- =>
- ->
Answer: ->. The arrow operator -> accesses an object's properties and methods, e.g. $rex->name.
What is the name of the special method that runs automatically on new?
- __init
- __construct
- __new
- __start
Answer: __construct. __construct() is the constructor; it runs the instant you write new.
What does $this refer to inside a method?
- The specific object the method is running on
- The class itself
- A global variable
- The parent class
Answer: The specific object the method is running on. $this is a reference to the particular object the method is being called on.
What does private visibility mean for a property?
- Anyone can read and write it
- It can never be set
- Only code inside the same class can access it
- It is shared across all objects
Answer: Only code inside the same class can access it. private restricts access to code inside the same class; outsiders use methods like getters.
What does constructor property promotion let you do?
- Make all properties public
- Declare a property and assign it in one step in the constructor signature
- Skip the constructor entirely
- Make a property readonly only
Answer: Declare a property and assign it in one step in the constructor signature. Putting a visibility keyword in the constructor's parameter list declares the property and assigns it.
How do you reach a static member from inside its own class?
- $this->
- new
- ->
- self::
Answer: self::. Inside the class you use self:: (e.g. self::$count) to reach static members and constants.
What is true of a readonly property (PHP 8.1)?
- It can never be set
- It can be set once, then never changed
- It is always public
- It is shared across objects
Answer: It can be set once, then never changed. A readonly property is assigned once (usually in the constructor) and locked thereafter.
What does a static property belong to?
- Each individual object
- The parent class only
- The class itself, shared by all
- A global scope
Answer: The class itself, shared by all. A static property has one shared copy on the class, reachable with Class::member.
Continue this course
- Previous: Sessions & Cookies
- Next: Database Integration