What is it?
OOP organises code around objects — things that have data (properties) and behaviour (methods). A class is the blueprint; an object is an instance built from that blueprint.
Why does it matter?
OOP reduces duplication and improves organisation. Instead of 20 scattered functions for users, you have a User class with all user-related logic in one place — easier to maintain, test, and extend.
A beginner introduction to OOP PHP — classes, objects, properties, methods, constructors.
Real-World Use Cases
- 👤 User management - A User class holds id, name, email as properties and login(), logout(), updateProfile() as methods.
- 💳 Payment processing - A Payment class encapsulates amount, currency, and status with pay(), refund(), getReceipt() methods.
- 📧 Email service - An Mailer class holds SMTP config in private properties and exposes only a simple send() method publicly.
- 🛒 Shopping cart - A Cart class manages items internally with addItem(), removeItem(), getTotal() methods and protects the internal array from direct modification.
Defining a Class
<?php
// Defining a Class
class Student {
// Properties
public $name;
public $age;
// Method
public function showDetails() {
echo "Name: " . $this->name . "<br>";
echo "Age: " . $this->age;
}
}
?>
Creating and Using Objects
<?php
$student1 = new Student();
$student1->name = "Rahul";
$student1->age = 22;
$student1->showDetails();
?>
Access Modifiers: public, private, protected
<?php
class Demo {
// Public property
public $name = "Rahul";
// Private property
private $salary = 50000;
// Protected property
protected $city = "Delhi";
// Public method
public function showPublic() {
echo "Public: " . $this->name . "<br>";
}
// Private method access inside class
public function showPrivate() {
echo "Private: " . $this->salary . "<br>";
}
// Protected method access inside class
public function showProtected() {
echo "Protected: " . $this->city . "<br>";
}
}
// Child class
class Employee extends Demo {
public function accessProtected() {
echo "Protected from Child Class: " . $this->city . "<br>";
}
}
// Object
$obj = new Employee();
// Public access
echo $obj->name . "<br>";
// Public method
$obj->showPublic();
// Private through public method
$obj->showPrivate();
// Protected through public method
$obj->showProtected();
// Protected in child class
$obj->accessProtected();
// Wrong Access
// echo $obj->salary;
// echo $obj->city;
?>
Q: What is $this in PHP?
$this refers to the current object inside a method. It lets you access the object's own properties and methods. Think of it as the object referring to itself.
Comments (0)
No comments yet. Be the first!
Leave a Comment