PHP Object-Oriented Programming (OOP)
Learn the fundamentals of object-oriented programming in PHP and how to create and use classes and objects.
Introduction to OOP
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and methods. PHP supports OOP, allowing developers to create reusable code and build more organized applications.
Core Concepts of OOP
The main concepts of OOP in PHP include:
- Classes and Objects
- Encapsulation
- Inheritance
- Polymorphism
Classes and Objects
A class is a blueprint for creating objects. An object is an instance of a class.
<?php
class Car {
public $color;
public $model;
public function __construct($color, $model) {
$this->color = $color;
$this->model = $model;
}
public function display() {
return "Car model: " . $this->model . ", Color: " . $this->color;
}
}
$myCar = new Car("red", "Toyota");
echo $myCar->display(); // Outputs: Car model: Toyota, Color: red
?>
Encapsulation
Encapsulation is the bundling of data (properties) and methods that operate on that data into a single unit (class). It restricts access to certain components using visibility keywords.
<?php
class BankAccount {
private $balance;
public function __construct($initialBalance) {
$this->balance = $initialBalance;
}
public function deposit($amount) {
$this->balance += $amount;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount(100);
$account->deposit(50);
echo $account->getBalance(); // Outputs: 150
?>
Inheritance
Inheritance allows a class to inherit properties and methods from another class. This promotes code reusability.
<?php
class Animal {
public function speak() {
return "Animal speaks";
}
}
class Dog extends Animal {
public function speak() {
return "Dog barks";
}
}
$dog = new Dog();
echo $dog->speak(); // Outputs: Dog barks
?>
Polymorphism
Polymorphism allows methods to do different things based on the object that it is acting upon, even if they share the same name.
<?php
class Cat extends Animal {
public function speak() {
return "Cat meows";
}
}
function animalSound(Animal $animal) {
echo $animal->speak();
}
$dog = new Dog();
$cat = new Cat();
animalSound($dog); // Outputs: Dog barks
animalSound($cat); // Outputs: Cat meows
?>
Conclusion
PHP Object-Oriented Programming is a powerful way to structure your code. By understanding the core concepts of classes, objects, encapsulation, inheritance, and polymorphism, you can create more organized, reusable, and maintainable applications.