PHP isn’t just about writing procedural code; it also supports Object-Oriented Programming (OOP)! OOP makes code cleaner, reusable, and easier to maintain. In this guide, we’ll break down OOP in PHP with fun explanations and real-world examples. Let’s dive in!
What is OOP?
Object-Oriented Programming (OOP) is a programming style based on objects rather than functions. Objects have properties (variables) and methods (functions) that define their behavior.
Imagine you’re designing a Car class in PHP. It would have:
- Properties:
color
,brand
,speed
- Methods:
start()
,accelerate()
,brake()
Creating a Class and Object in PHP
Example: Defining a Car
Class
class Car {
public $brand;
public $color;
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
public function drive() {
return "The $this->color $this->brand is driving!";
}
}
$myCar = new Car("Toyota", "red");
echo $myCar->drive();
// Output: The red Toyota is driving!
OOP Concepts in PHP
Encapsulation (Data Hiding)
Encapsulation protects object data by restricting direct access.
class BankAccount {
private $balance = 0;
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(500);
echo $account->getBalance();
// Output: 500
Inheritance (Extending Classes)
Inheritance lets a class inherit properties and methods from another class.
class Animal {
public function makeSound() {
return "Some generic animal sound!";
}
}
class Dog extends Animal {
public function makeSound() {
return "Woof!";
}
}
$dog = new Dog();
echo $dog->makeSound();
// Output: Woof!
Polymorphism (Method Overriding)
Polymorphism allows a child class to override a parent method.
class Bird {
public function fly() {
return "Flying high!";
}
}
class Penguin extends Bird {
public function fly() {
return "I can't fly, but I can swim!";
}
}
$penguin = new Penguin();
echo $penguin->fly();
// Output: I can't fly, but I can swim!
Abstraction (Hiding Implementation)
Abstract classes define a blueprint but can’t be instantiated directly.
abstract class Animal {
abstract public function makeSound();
}
class Cat extends Animal {
public function makeSound() {
return "Meow!";
}
}
$cat = new Cat();
echo $cat->makeSound();
// Output: Meow!
Real-World Example: User Authentication System
class User {
private $username;
private $password;
public function __construct($username, $password) {
$this->username = $username;
$this->password = password_hash($password, PASSWORD_DEFAULT);
}
public function login($inputPassword) {
if (password_verify($inputPassword, $this->password)) {
return "Login successful!";
}
return "Invalid password!";
}
}
$user = new User("JohnDoe", "secure123");
echo $user->login("secure123");
// Output: Login successful!
Now you understand OOP in PHP with real-world examples! Classes & Objects, Encapsulation, Inheritance, Polymorphism, Abstraction.
0 Comments