You are currently viewing Introduction to Object-Oriented Programming (OOP) in PHP: A Comprehensive Tutorial

Introduction to Object-Oriented Programming (OOP) in PHP: A Comprehensive Tutorial

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments
  • Post last modified:May 17, 2024

Introduction to Object-Oriented Programming (OOP) in PHP: A Comprehensive Tutorial

Table of Contents

  1. What is OOP?
  2. Classes and Objects
  3. Properties and Methods
  4. Constructors and Destructors
  5. Inheritance
  6. Access Modifiers
  7. Polymorphism
  8. Interfaces and Abstract Classes
  9. Example: Building a Simple Application
  10. Conclusion

What is OOP?

Object-Oriented Programming is a method of programming where you define the data structure as objects, which are instances of classes. A class is like a blueprint for an object. It defines properties (attributes) and methods (functions) that the object can use.

Classes and Objects

A class in PHP is defined using the class keyword followed by the class name. Here is an example:

class Car {
    // Properties
    public $make;
    public $model;
    public $year;

    // Methods
    public function displayDetails() {
        echo "Make: " . $this->make . ", Model: " . $this->model . ", Year: " . $this->year;
    }
}

// Creating an object
$car1 = new Car();
$car1->make = 'Toyota';
$car1->model = 'Corolla';
$car1->year = 2020;
$car1->displayDetails();  // Output: Make: Toyota, Model: Corolla, Year: 2020

In this example, Car is a class with three properties (make, model, and year) and one method (displayDetails). We create an object $car1 of the class Car and set its properties.

Properties and Methods

Properties are variables that belong to a class. Methods are functions that belong to a class. They define the behavior of the objects created from the class.

class Person {
    public $name;
    public $age;

    public function sayHello() {
        echo "Hello, my name is " . $this->name;
    }
}

$person1 = new Person();
$person1->name = 'John';
$person1->age = 30;
$person1->sayHello();  // Output: Hello, my name is John

Constructors and Destructors

Constructors are special methods that are automatically called when an object is created. Destructors are called when an object is destroyed.

class Book {
    public $title;
    public $author;

    // Constructor
    public function __construct($title, $author) {
        $this->title = $title;
        $this->author = $author;
    }

    // Destructor
    public function __destruct() {
        echo "The book titled '{$this->title}' is now out of scope.";
    }
}

$book1 = new Book('1984', 'George Orwell');
echo $book1->title;  // Output: 1984

Inheritance

Inheritance allows a class to inherit properties and methods from another class. The class that inherits is called the child class, and the class being inherited from is the parent class.

class Animal {
    public $name;

    public function speak() {
        echo "Animal sound";
    }
}

class Dog extends Animal {
    public function speak() {
        echo "Bark";
    }
}

$dog = new Dog();
$dog->name = 'Rover';
$dog->speak();  // Output: Bark

Access Modifiers

Access modifiers define the visibility of properties and methods. PHP has three access modifiers:

  • public: The property or method can be accessed from anywhere.
  • protected: The property or method can be accessed within the class and by classes derived from that class.
  • private: The property or method can only be accessed within the class.
class MyClass {
    public $publicProp = 'Public';
    protected $protectedProp = 'Protected';
    private $privateProp = 'Private';

    public function showProperties() {
        echo $this->publicProp;
        echo $this->protectedProp;
        echo $this->privateProp;
    }
}

$obj = new MyClass();
echo $obj->publicProp;  // Output: Public
$obj->showProperties(); // Output: PublicProtectedPrivate

Polymorphism

Polymorphism allows methods to do different things based on the object it is acting upon, even if they share the same name.

class Shape {
    public function draw() {
        echo "Drawing a shape";
    }
}

class Circle extends Shape {
    public function draw() {
        echo "Drawing a circle";
    }
}

class Square extends Shape {
    public function draw() {
        echo "Drawing a square";
    }
}

$shapes = [new Circle(), new Square(), new Shape()];

foreach ($shapes as $shape) {
    $shape->draw();
}
// Output:
// Drawing a circle
// Drawing a square
// Drawing a shape

Interfaces and Abstract Classes

Interfaces and abstract classes are used to define methods that must be implemented in the derived classes.

Interface

interface Logger {
    public function log($message);
}

class FileLogger implements Logger {
    public function log($message) {
        echo "Logging message to a file: $message";
    }
}

$logger = new FileLogger();
$logger->log("An error occurred");  // Output: Logging message to a file: An error occurred

Abstract Class

abstract class Animal {
    abstract public function makeSound();

    public function eat() {
        echo "Eating";
    }
}

class Cat extends Animal {
    public function makeSound() {
        echo "Meow";
    }
}

$cat = new Cat();
$cat->makeSound();  // Output: Meow
$cat->eat();        // Output: Eating

Example: Building a Simple Application

Let’s build a simple application to manage a list of employees using OOP principles.

class Employee {
    public $name;
    public $position;
    public $salary;

    public function __construct($name, $position, $salary) {
        $this->name = $name;
        $this->position = $position;
        $this->salary = $salary;
    }

    public function displayEmployeeInfo() {
        echo "Name: " . $this->name . ", Position: " . $this->position . ", Salary: $" . $this->salary . "<br>";
    }
}

class EmployeeList {
    private $employees = [];

    public function addEmployee(Employee $employee) {
        $this->employees[] = $employee;
    }

    public function displayEmployees() {
        foreach ($this->employees as $employee) {
            $employee->displayEmployeeInfo();
        }
    }
}

$employee1 = new Employee('Alice', 'Developer', 60000);
$employee2 = new Employee('Bob', 'Designer', 55000);

$employeeList = new EmployeeList();
$employeeList->addEmployee($employee1);
$employeeList->addEmployee($employee2);

$employeeList->displayEmployees();
// Output:
// Name: Alice, Position: Developer, Salary: $60000
// Name: Bob, Position: Designer, Salary: $55000

Conclusion

In this tutorial, we covered the fundamental concepts of Object-Oriented Programming in PHP, including classes, objects, properties, methods, constructors, destructors, inheritance, access modifiers, polymorphism, interfaces, and abstract classes. We also built a simple application to demonstrate how these concepts work together. With these basics, you can start leveraging OOP to write more organized and maintainable PHP code.

Leave a Reply