Object-Oriented PHP
Model real things with classes and objects — the foundation Laravel is built on.
What you will learn
- Define classes with properties and methods
- Create objects
- Use $this and the constructor
Classes and objects
A class is a blueprint; an object is an instance built from it. Think of the class as a cookie cutter and each object as a cookie. Properties are its data (like name); methods are its functions (like greet()). $this refers to the current object — "me, this particular cookie".
<?php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name; // -> accesses properties
$this->email = $email;
}
public function greet() {
return "Hi, I am " . $this->name;
}
}
$asha = new User("Asha", "asha@x.com");
echo $asha->greet(); // Hi, I am Asha
echo $asha->email; // asha@x.com
?>Walking through it: the class User block is just the blueprint — nothing happens until new User("Asha", "asha@x.com") builds an actual object. Creating it runs the __construct method, which copies the two values into $this->name and $this->email — that object’s own data. Then $asha->greet() calls the object’s method (which reads its own $this->name), and $asha->email reads its stored property directly.
Note: Output (in the browser):
Hi, I am Ashaasha@x.com
The object $asha carries its own data and behaviour together. Build a second object — $ravi = new User("Ravi", "ravi@x.com") — and $ravi->greet() would say "Hi, I am Ravi", because $this always means *that* object.
class User { }— the blueprint.__construct— runs when you create the object (new User(...)).$this->name— the object’s own property.->— the arrow to access properties and methods.
Note: This is the heart of modern PHP. Laravel models, controllers and almost everything are classes — master OOP here and Laravel will feel natural.
Q. Inside a class method, what does $this refer to?
✍️ Practice
- Create a
Productclass with name and price and a method that returns a label. - Create two objects from it.
🏠 Homework
- Build a
BankAccountclass with a balance, deposit() and withdraw() methods.