We will discus in this topic OOP in PHP in a structured, beginner-friendly way
- What is OOP?
- Core OOP Concepts in PHP
- Detailed example
- Mini Project (User Management System – practical implementation)
What is OOP?
OOP (Object Oriented Programming) is a programming paradigm where we structure code using:
- Class → Blueprint
- Object → Instance of class
- Properties → Variables inside class
- Methods → Functions inside class
Instead of writing procedural code, we model real-world entities.
Core OOP Concepts in PHP
Class & Object
<?php
class Car {
public $brand;
public $color;
public function start() {
echo "Car is starting...";
}
}
$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";
$car1->start();
?>
Detailed Explanation
➡ Defines a class named Car.
class Car {
➡ Properties (variables) inside class.
➡ public means accessible from anywhere.
public $brand;
public $color;
➡ Method (function inside class).
➡ Prints message.
Class Method
public function start() {
echo "Car is starting...";
}
Create Object(Instance)
$car1 = new Car();
Assign Value to object
We can assign value to class vaiables using object notation operator '->' like below
$car1->brand = "Toyota";
Constructor
A constructor runs automatically when an object is created.
Constructor
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello " . $this->name;
}
}
$user = new User("Amit");
echo $user->greet();
Important Concept
$this->name ➡ $this refers to current object.
Encapsulation
Hiding data using private or protected.
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
You cannot access:
$account->balance; ❌ (Error)
Only through method:
echo $account->getBalance();
Inheritance
Child class extends parent class.
class Animal {
public function sound() {
echo "Animal makes sound";
}
}
class Dog extends Animal {
public function bark() {
echo "Dog barks";
}
}
Dog inherits sound() method.
Polymorphism
Same method name, different behavior.
class Shape {
public function area() {
return 0;
}
}
class Circle extends Shape {
private $radius;
public function __construct($r) {
$this->radius = $r;
}
public function area() {
return 3.14 * $this->radius * $this->radius;
}
}