Published by Hashan Madhushanka
- 03 min read
Object Oriented PHP Fundamentals
Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects rather than functions and logic. This guide covers the fundamental concepts you need to understand OOP in PHP.
Understanding Classes and Objects
A class is a blueprint that defines properties and methods. An object is an instance of a class.
class Car {
public $brand;
public $color;
public function drive() {
return "The car is driving";
}
}
// Creating an object
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->color = "Red";
echo $myCar->drive();
Properties and Methods
Properties are variables that belong to a class. Methods are functions that belong to a class.
class Rectangle {
public $width;
public $height;
public function calculateArea() {
return $this->width * $this->height;
}
}
$rectangle = new Rectangle();
$rectangle->width = 10;
$rectangle->height = 5;
echo $rectangle->calculateArea(); // Output: 50
The $this keyword refers to the current object instance.
Constructors
A constructor is a special method that automatically executes when an object is created. It’s defined using __construct().
class Book {
public $title;
public $author;
public $pages;
public function __construct($title, $author, $pages) {
$this->title = $title;
$this->author = $author;
$this->pages = $pages;
}
public function getDescription() {
return $this->title . " by " . $this->author;
}
}
$book = new Book("1984", "George Orwell", 328);
echo $book->getDescription();
Access Modifiers
Access modifiers control the visibility of properties and methods:
- public: Accessible from anywhere
- private: Accessible only within the class
- protected: Accessible within the class and by inheriting classes
class User {
public $username;
private $password;
protected $email;
public function __construct($username, $password, $email) {
$this->username = $username;
$this->password = $password;
$this->email = $email;
}
public function setPassword($newPassword) {
$this->password = password_hash($newPassword, PASSWORD_DEFAULT);
}
public function verifyPassword($inputPassword) {
return password_verify($inputPassword, $this->password);
}
}
$user = new User("john_doe", "secret123", "[email protected]");
echo $user->username; // Works - public property
// echo $user->password; // Error - private property
$user->setPassword("newSecret456"); // Works - public method
Encapsulation
Encapsulation is the practice of hiding internal data and exposing only what’s necessary through public methods (getters and setters).
class BankAccount {
private $balance;
private $accountNumber;
public function __construct($accountNumber, $initialBalance) {
$this->accountNumber = $accountNumber;
$this->balance = $initialBalance;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
return true;
}
return false;
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
return true;
}
return false;
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount("123456", 1000);
$account->deposit(500);
$account->withdraw(200);
echo $account->getBalance(); // Output: 1300
Inheritance
Inheritance allows a class to inherit properties and methods from another class using the extends keyword.
class Vehicle {
protected $brand;
protected $year;
public function __construct($brand, $year) {
$this->brand = $brand;
$this->year = $year;
}
public function getInfo() {
return $this->year . " " . $this->brand;
}
}
class Car extends Vehicle {
private $doors;
public function __construct($brand, $year, $doors) {
parent::__construct($brand, $year);
$this->doors = $doors;
}
public function getCarInfo() {
return $this->getInfo() . " with " . $this->doors . " doors";
}
}
$car = new Car("Honda", 2023, 4);
echo $car->getCarInfo(); // Output: 2023 Honda with 4 doors
The parent:: keyword is used to call methods from the parent class.
Polymorphism
Polymorphism allows objects of different classes to be treated as objects of a common parent class. It’s often implemented through method overriding.
class Animal {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function makeSound() {
return "Some generic sound";
}
}
class Dog extends Animal {
public function makeSound() {
return $this->name . " barks: Woof!";
}
}
class Cat extends Animal {
public function makeSound() {
return $this->name . " meows: Meow!";
}
}
$animals = [
new Dog("Rex"),
new Cat("Whiskers"),
new Dog("Buddy")
];
foreach ($animals as $animal) {
echo $animal->makeSound() . "\n";
}
Abstract Classes
Abstract classes cannot be instantiated and are meant to be extended. They can contain abstract methods that must be implemented by child classes.
abstract class Shape {
abstract public function calculateArea();
abstract public function calculatePerimeter();
public function describe() {
return "This is a shape";
}
}
class Circle extends Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
public function calculatePerimeter() {
return 2 * pi() * $this->radius;
}
}
$circle = new Circle(5);
echo $circle->calculateArea(); // Output: 78.539816339745
Interfaces
Interfaces define a contract that classes must follow. They contain only method signatures without implementation.
interface PaymentInterface {
public function processPayment($amount);
public function refund($transactionId);
}
class CreditCardPayment implements PaymentInterface {
public function processPayment($amount) {
return "Processing credit card payment of $" . $amount;
}
public function refund($transactionId) {
return "Refunding transaction " . $transactionId;
}
}
class PayPalPayment implements PaymentInterface {
public function processPayment($amount) {
return "Processing PayPal payment of $" . $amount;
}
public function refund($transactionId) {
return "Refunding PayPal transaction " . $transactionId;
}
}
$payment = new CreditCardPayment();
echo $payment->processPayment(100);
A class can implement multiple interfaces but can only extend one class.
Static Properties and Methods
Static members belong to the class itself rather than to any object instance. They’re accessed using the :: operator.
class MathHelper {
public static $pi = 3.14159;
public static function square($number) {
return $number * $number;
}
public static function cube($number) {
return $number * $number * $number;
}
}
echo MathHelper::$pi; // Output: 3.14159
echo MathHelper::square(5); // Output: 25
echo MathHelper::cube(3); // Output: 27
Constants
Constants are values that cannot be changed. They’re defined using the const keyword.
class Database {
const HOST = 'localhost';
const USERNAME = 'root';
const PASSWORD = '';
public function connect() {
return "Connecting to " . self::HOST;
}
}
echo Database::HOST; // Output: localhost
Use self:: to access constants within the class.
Key Principles Summary
Encapsulation: Bundle data and methods together, hide internal details.
Inheritance: Reuse code by creating child classes from parent classes.
Polymorphism: Use a unified interface for different data types.
Abstraction: Hide complex implementation details, expose only necessary parts.
These four principles form the foundation of Object-Oriented Programming and enable you to write more maintainable, reusable, and organized code.