OOP - potatoscript/php GitHub Wiki

Object-Oriented Programming (OOP) in PHP

Overview

Object-Oriented Programming (OOP) is a programming paradigm that uses "objects" to represent data and methods. OOP helps organize code, making it more modular, reusable, and easier to maintain. In PHP, OOP is fully supported and widely used to develop large-scale applications.

In this section, we will cover:

  • Basics of OOP
  • Classes and Objects
  • Properties and Methods
  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction
  • Access Modifiers

Basics of OOP

OOP is built around the concept of classes and objects. A class is like a blueprint for an object, and an object is an instance of a class. PHP allows developers to define classes, create objects, and use various OOP features like inheritance, polymorphism, and encapsulation.

Key Concepts in OOP:

  1. Class: A template or blueprint for creating objects.
  2. Object: An instance of a class.
  3. Method: A function defined within a class.
  4. Property: A variable defined within a class.

Classes and Objects

Defining a Class

A class in PHP is defined using the class keyword followed by the class name and a block of code that contains properties and methods.

<?php
class Car {
    // Properties
    public $make;
    public $model;
    public $year;

    // Method
    public function displayInfo() {
        return $this->year . ' ' . $this->make . ' ' . $this->model;
    }
}

// Creating an Object
$myCar = new Car();
$myCar->make = "Toyota";
$myCar->model = "Corolla";
$myCar->year = 2020;

echo $myCar->displayInfo();  // Output: 2020 Toyota Corolla
?>

Explanation:

  • Car is a class with properties $make, $model, and $year.
  • The displayInfo() method returns a string with the car's information.
  • The object $myCar is created using the new keyword, and its properties are set. The method is then called on the object.

Properties and Methods

Properties

Properties are variables that are defined inside a class. They represent the attributes or characteristics of an object.

class Person {
    public $name;
    public $age;

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

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

$person = new Person("John", 30);
echo $person->greet();  // Output: Hello, my name is John

Methods

Methods are functions defined inside a class. They define the behavior of an object.

class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }
}

$calc = new Calculator();
echo $calc->add(3, 5);  // Output: 8

Constructor and Destructor

  • Constructor: A special method that is called when an object is instantiated.
  • Destructor: A special method that is called when an object is destroyed.
class Example {
    public function __construct() {
        echo "Object created!";
    }

    public function __destruct() {
        echo "Object destroyed!";
    }
}

$obj = new Example();  // Output: Object created!
unset($obj);            // Output: Object destroyed!

Inheritance

Inheritance allows a class to inherit properties and methods from another class, which promotes code reuse and organization.

Example: Inheritance

class Animal {
    public $name;

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

    public function speak() {
        return $this->name . " makes a sound";
    }
}

class Dog extends Animal {
    public function speak() {
        return $this->name . " barks";
    }
}

$dog = new Dog("Buddy");
echo $dog->speak();  // Output: Buddy barks

Explanation:

  • Dog is a subclass of Animal. It inherits the $name property and the speak() method.
  • The speak() method is overridden in the Dog class to give it specific functionality.

Polymorphism

Polymorphism allows methods to have the same name but behave differently based on the object that invokes them.

Example: Polymorphism

class Bird {
    public function speak() {
        return "Tweet tweet!";
    }
}

class Dog {
    public function speak() {
        return "Woof woof!";
    }
}

function animalSound($animal) {
    echo $animal->speak();
}

$bird = new Bird();
$dog = new Dog();

animalSound($bird);  // Output: Tweet tweet!
animalSound($dog);   // Output: Woof woof!

Explanation:

  • Both Bird and Dog have a speak() method, but they produce different outputs.
  • The animalSound() function can accept any object that has a speak() method.

Encapsulation

Encapsulation is the concept of restricting access to certain details of an object and providing public methods to interact with the object's data.

Example: Encapsulation

class BankAccount {
    private $balance;

    public function __construct($balance) {
        $this->balance = $balance;
    }

    public function deposit($amount) {
        $this->balance += $amount;
    }

    public function getBalance() {
        return $this->balance;
    }
}

$account = new BankAccount(1000);
$account->deposit(500);
echo $account->getBalance();  // Output: 1500

Explanation:

  • The $balance property is private and cannot be accessed directly from outside the class.
  • Public methods deposit() and getBalance() are used to modify and access the balance.

Abstraction

Abstraction allows hiding complex implementation details and showing only the essential features of an object. In PHP, abstract classes and interfaces are used to achieve abstraction.

Example: Abstract Class

abstract class Shape {
    abstract public function area();
}

class Rectangle extends Shape {
    public $width;
    public $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function area() {
        return $this->width * $this->height;
    }
}

$rect = new Rectangle(5, 10);
echo $rect->area();  // Output: 50

Explanation:

  • Shape is an abstract class with an abstract method area().
  • The Rectangle class extends Shape and implements the area() method.

Access Modifiers

Access modifiers control the visibility of class properties and methods. PHP supports three access modifiers:

  • public: The property or method is accessible from anywhere.
  • protected: The property or method is accessible within the class and by derived classes.
  • private: The property or method is only accessible within the class itself.

Example: Access Modifiers

class MyClass {
    public $publicVar;
    protected $protectedVar;
    private $privateVar;

    public function __construct() {
        $this->publicVar = "Public";
        $this->protectedVar = "Protected";
        $this->privateVar = "Private";
    }

    public function display() {
        echo $this->publicVar;    // Accessible
        echo $this->protectedVar; // Accessible
        echo $this->privateVar;   // Accessible
    }
}

$obj = new MyClass();
echo $obj->publicVar;         // Accessible
// echo $obj->protectedVar;    // Error: Cannot access protected property
// echo $obj->privateVar;      // Error: Cannot access private property
?>

Conclusion

In this section, we covered the fundamental concepts of Object-Oriented Programming (OOP) in PHP:

  • Classes and Objects for creating reusable code structures.
  • Properties and Methods for defining object attributes and behaviors.
  • Inheritance for reusing code through class extensions.
  • Polymorphism for using the same method name with different behaviors.
  • Encapsulation for controlling access to an object's internal state.
  • Abstraction for hiding complex logic and exposing only essential features.
  • Access Modifiers for controlling the visibility of class members.

By understanding and using OOP, you can create more structured, modular, and maintainable PHP applications.