Object Oriented Programming(OOP) in PHP
PHP supports Object-Oriented Programming (OOP), allowing developers to use classes and objects to structure their code. Here's an overview of key OOP concepts in PHP:
A class is a blueprint for creating objects. It defines properties (attributes) and methods (functions) that the objects will have.
class Car {
// Properties
public $make;
public $model;
// Methods
public function startEngine() {
echo "Engine started!";
}
}
Objects are instances of a class. You create objects using the new
keyword.
// Create an object of the Car class
$myCar = new Car();
// Accessing properties and calling methods
$myCar->make = "Toyota";
$myCar->model = "Camry";
$myCar->startEngine();
A constructor is a special method that is automatically called when an object is created. It is used to initialize object properties.
class Car {
public $make;
public $model;
// Constructor
public function __construct($make, $model) {
$this->make = $make;
$this->model = $model;
}
}
A destructor is a special method that is automatically called when an object is no longer referenced. It can be used to perform cleanup tasks.
class Car {
// ...
// Destructor
public function __destruct() {
echo "Car object destroyed!";
}
}
Inheritance allows a class to inherit properties and methods from another class. The extends
keyword is used for inheritance.
class Truck extends Car {
public $payload;
public function loadCargo() {
echo "Cargo loaded!";
}
}
Encapsulation involves bundling the data (properties) and methods that operate on the data within a single unit (class). Properties are often declared as private or protected, and public methods are used to access or modify them.
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
Polymorphism allows objects of different types to be treated as objects of a common base type. It is achieved through method overriding and interfaces.
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
public $radius;
public function calculateArea() {
return 3.14 * $this->radius * $this->radius;
}
}
class Rectangle implements Shape {
public $length;
public $width;
public function calculateArea() {
return $this->length * $this->width;
}
}
Abstraction involves simplifying complex systems by modeling classes based on essential properties and behaviors. Abstract classes and interfaces are used to achieve abstraction.
abstract class Shape {
abstract public function calculateArea();
}
class Circle extends Shape {
// ...
}
class Rectangle extends Shape {
// ...
}
These are some of the fundamental concepts of Object-Oriented Programming in PHP. They provide a structured and modular approach to software development, making it easier to design, maintain, and scale applications.
Thank you.