Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to structure software. PHP supports OOP, allowing developers to write modular, reusable, and maintainable code.
A class is a blueprint for creating objects. An object is an instance of a class.
<?php
class Car {
// Properties
public $brand;
public $model;
// Constructor
public function __construct($brand, $model) {
$this->brand = $brand;
$this->model = $model;
}
// Method
public function displayInfo() {
return "This car is a {$this->brand} {$this->model}.";
}
}
// Create an object
$myCar = new Car("Toyota", "Corolla");
echo $myCar->displayInfo();
?>
In this example, Car is a class, and $myCar is an object of the Car class.
Inheritance allows a class to inherit properties and methods from another class.
<?php
class Vehicle {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
public function displayBrand() {
return "This vehicle is a {$this->brand}.";
}
}
class Car extends Vehicle {
public $model;
public function __construct($brand, $model) {
parent::__construct($brand);
$this->model = $model;
}
public function displayInfo() {
return parent::displayBrand() . " Model: {$this->model}";
}
}
$myCar = new Car("Toyota", "Corolla");
echo $myCar->displayInfo();
?>
Here, the Car class inherits from the Vehicle class.
Encapsulation is the bundling of data with the methods that operate on that data. It restricts direct access to some of an object's components.
<?php
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function withdraw($amount) {
if ($amount <= $this->balance) {
$this->balance -= $amount;
} else {
echo "Insufficient balance.";
}
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(1000);
$account->withdraw(500);
echo "Balance: " . $account->getBalance();
?>
The balance property is private and can only be accessed through public methods.
Polymorphism allows objects of different classes to be treated as objects of a common super class.
<?php
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
return "Woof!";
}
}
class Cat implements Animal {
public function makeSound() {
return "Meow!";
}
}
$animals = [new Dog(), new Cat()];
foreach ($animals as $animal) {
echo $animal->makeSound() . "<br>";
}
?>
Both Dog and Cat implement the Animal interface, allowing them to be treated as Animal objects.