PHP OOP
Object-Oriented Programming fundamentals in PHP
🎯 What is OOP?
Object-Oriented Programming (OOP) organizes code into reusable objects with properties and methods. It promotes code reusability, modularity, and easier maintenance through concepts like classes, inheritance, encapsulation, and polymorphism.
<?php
// Define a class
class Car {
public $brand;
public function drive() {
return "Driving a {$this->brand}";
}
}
// Create an object
$myCar = new Car();
$myCar->brand = "Toyota";
echo $myCar->drive(); // Output: Driving a Toyota
?>
Output:
Driving a Toyota
OOP Core Concepts
Classes & Objects
Classes are blueprints for creating objects. Objects are instances of classes with their own property values.
<?php
class Person {
public $name;
}
$person = new Person();
$person->name = "John";
?>
Encapsulation
Hide internal details using private/protected properties and provide public methods to access them safely.
<?php
class Account {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
}
?>
Inheritance
Create new classes based on existing ones, inheriting properties and methods while adding new functionality.
<?php
class Animal {
public function eat() {}
}
class Dog extends Animal {
public function bark() {}
}
?>
Polymorphism
Different classes can implement the same method in different ways, allowing flexible code design.
<?php
interface Shape {
public function area();
}
class Circle implements Shape {
public function area() {}
}
?>
🔹 Creating Classes and Objects
Define a class and create objects from it:
<?php
class Book {
// Properties
public $title;
public $author;
public $pages;
// Method
public function getInfo() {
return "{$this->title} by {$this->author} ({$this->pages} pages)";
}
}
// Create objects
$book1 = new Book();
$book1->title = "PHP Basics";
$book1->author = "John Doe";
$book1->pages = 250;
$book2 = new Book();
$book2->title = "Advanced PHP";
$book2->author = "Jane Smith";
$book2->pages = 400;
echo $book1->getInfo() . "<br>";
echo $book2->getInfo();
?>
Output:
PHP Basics by John Doe (250 pages)
Advanced PHP by Jane Smith (400 pages)
🔹 Constructor and Destructor
Special methods that run when objects are created or destroyed:
<?php
class User {
public $name;
public $email;
// Constructor - runs when object is created
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
echo "User {$this->name} created<br>";
}
// Destructor - runs when object is destroyed
public function __destruct() {
echo "User {$this->name} destroyed<br>";
}
}
$user1 = new User("Alice", "[email protected]");
$user2 = new User("Bob", "[email protected]");
?>
Output:
User Alice created
User Bob created
User Bob destroyed
User Alice destroyed
🔹 Access Modifiers
Control visibility of properties and methods:
<?php
class BankAccount {
public $accountNumber; // Accessible everywhere
protected $accountType; // Accessible in class and subclasses
private $balance = 0; // Only accessible in this class
public function __construct($number, $type) {
$this->accountNumber = $number;
$this->accountType = $type;
}
public function deposit($amount) {
$this->balance += $amount;
return "Deposited: $$amount";
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount("12345", "Savings");
echo $account->deposit(100) . "<br>";
echo "Balance: $" . $account->getBalance() . "<br>";
echo "Account: " . $account->accountNumber;
?>
Output:
Deposited: $100
Balance: $100
Account: 12345
🔹 Inheritance
Create child classes that inherit from parent classes:
<?php
// Parent class
class Vehicle {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function honk() {
return "Beep beep!";
}
}
// Child class
class Car extends Vehicle {
public $model;
public function __construct($brand, $model) {
parent::__construct($brand);
$this->model = $model;
}
public function getInfo() {
return "{$this->brand} {$this->model}";
}
}
$car = new Car("Toyota", "Camry");
echo $car->getInfo() . "<br>";
echo $car->honk();
?>
Output:
Toyota Camry
Beep beep!
🔹 Abstract Classes
Define template classes that cannot be instantiated directly:
<?php
abstract class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
// Abstract method - must be implemented by child classes
abstract public function makeSound();
// Regular method
public function sleep() {
return "{$this->name} is sleeping";
}
}
class Dog extends Animal {
public function makeSound() {
return "{$this->name} says: Woof!";
}
}
class Cat extends Animal {
public function makeSound() {
return "{$this->name} says: Meow!";
}
}
$dog = new Dog("Buddy");
$cat = new Cat("Whiskers");
echo $dog->makeSound() . "<br>";
echo $cat->makeSound() . "<br>";
echo $dog->sleep();
?>
Output:
Buddy says: Woof!
Whiskers says: Meow!
Buddy is sleeping
🔹 Interfaces
Define contracts that classes must implement:
<?php
interface PaymentInterface {
public function processPayment($amount);
public function refund($amount);
}
class CreditCard implements PaymentInterface {
public function processPayment($amount) {
return "Charged $$amount to credit card";
}
public function refund($amount) {
return "Refunded $$amount to credit card";
}
}
class PayPal implements PaymentInterface {
public function processPayment($amount) {
return "Paid $$amount via PayPal";
}
public function refund($amount) {
return "Refunded $$amount via PayPal";
}
}
$cc = new CreditCard();
$pp = new PayPal();
echo $cc->processPayment(100) . "<br>";
echo $pp->processPayment(50);
?>
Output:
Charged $100 to credit card
Paid $50 via PayPal
🔹 Static Properties and Methods
Access class members without creating an object:
<?php
class MathHelper {
public static $pi = 3.14159;
public static function square($number) {
return $number * $number;
}
public static function circleArea($radius) {
return self::$pi * self::square($radius);
}
}
// Access without creating object
echo "Pi: " . MathHelper::$pi . "<br>";
echo "5 squared: " . MathHelper::square(5) . "<br>";
echo "Circle area (r=3): " . MathHelper::circleArea(3);
?>
Output:
Pi: 3.14159
5 squared: 25
Circle area (r=3): 28.27431
🔹 OOP Best Practices
Design Principles:
- Single Responsibility - Each class should have one purpose
- Encapsulation - Keep data private, provide public methods
- DRY (Don't Repeat Yourself) - Reuse code through inheritance
- Composition over Inheritance - Prefer using objects over extending classes
- Program to Interfaces - Depend on abstractions, not concrete classes
Key OOP Features:
- Classes - Blueprints for objects
- Objects - Instances of classes
- Properties - Variables inside classes
- Methods - Functions inside classes
- Inheritance - Extend existing classes
- Interfaces - Define contracts for classes
- Abstract Classes - Template classes
- Static Members - Class-level properties/methods