PHP OOP



 

PHP OOP (Object-Oriented Programming)

Object-Oriented Programming (OOP) is a programming paradigm centered around the concept of "objects," which are instances of classes. PHP supports OOP, allowing developers to create reusable and modular code using classes, objects, properties, and methods.


1. Defining a Class

A class is a blueprint for creating objects. It can contain properties (variables) and methods (functions).

Example: Defining a Class

class Car {
    // Properties
    public $brand;
    public $model;
    
    // Constructor Method
    public function __construct($brand, $model) {
        $this->brand = $brand;
        $this->model = $model;
    }

    // Method
    public function getCarInfo() {
        return $this->brand . " " . $this->model;
    }
}

2. Creating an Object

To create an object from a class, use the new keyword.

Example: Creating an Object

$car1 = new Car("Toyota", "Corolla");
echo $car1->getCarInfo(); // Output: Toyota Corolla

3. Properties and Methods

Properties are variables that belong to an object, and methods are functions that belong to an object.

Example: Accessing Properties and Methods

$car1->brand = "Honda";
$car1->model = "Civic";
echo $car1->getCarInfo(); // Output: Honda Civic

4. Visibility (Access Modifiers)

PHP supports three visibility modifiers: public, protected, and private, which control access to class properties and methods.

  • Public: Accessible everywhere.
  • Protected: Accessible within the class and by derived classes.
  • Private: Accessible only within the class itself.

Example: Visibility Modifiers

class Vehicle {
    public $type = "Car"; // Public: accessible anywhere
    protected $fuel = "Gasoline"; // Protected: accessible in this class and child classes
    private $vin = "123456789"; // Private: accessible only in this class

    public function getVIN() {
        return $this->vin; // Can be accessed inside the class
    }
}

$vehicle = new Vehicle();
echo $vehicle->type; // Output: Car
// echo $vehicle->fuel; // Error: Cannot access protected property
// echo $vehicle->vin; // Error: Cannot access private property
echo $vehicle->getVIN(); // Output: 123456789

5. Inheritance

Inheritance allows a class to extend another class, inheriting its properties and methods.

Example: Class Inheritance

class Car extends Vehicle {
    public $brand;
    
    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function getBrand() {
        return $this->brand;
    }
}

$car1 = new Car("Toyota");
echo $car1->getBrand(); // Output: Toyota
echo $car1->type; // Output: Car (Inherited from Vehicle class)

6. Polymorphism (Method Overriding)

Polymorphism allows a child class to modify the behavior of a method inherited from its parent class.

Example: Method Overriding

class Animal {
    public function sound() {
        return "Some sound";
    }
}

class Dog extends Animal {
    public function sound() {
        return "Bark"; // Overriding the parent method
    }
}

$dog = new Dog();
echo $dog->sound(); // Output: Bark

7. Static Methods and Properties

Static methods and properties belong to the class itself, not to instances of the class. They can be accessed without creating an object.

Example: Static Property and Method

class Calculator {
    public static $pi = 3.1416;

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

echo Calculator::$pi; // Output: 3.1416
echo Calculator::add(5, 10); // Output: 15

8. Abstract Classes

An abstract class cannot be instantiated on its own and must be extended by other classes. It can contain abstract methods, which must be implemented by child classes.

Example: Abstract Class

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

class Circle extends Shape {
    public $radius;

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

    public function area() {
        return 3.1416 * $this->radius * $this->radius;
    }
}

$circle = new Circle(5);
echo $circle->area(); // Output: 78.54

9. Interfaces

An interface defines methods that must be implemented by any class that implements the interface. It cannot contain any properties or method implementations.

Example: 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("Hello, World!"); // Output: Logging message to a file: Hello, World!

10. Traits

Traits allow code reuse across multiple classes without inheritance. They provide a way to share methods between classes.

Example: Using Traits

trait LoggerTrait {
    public function log($message) {
        echo "Log: $message";
    }
}

class User {
    use LoggerTrait; // Include the trait
}

$user = new User();
$user->log("User created"); // Output: Log: User created

11. Complete Example: OOP in PHP

Here's a complete example combining many of the OOP concepts.

Example: Full Script

class Product {
    public $name;
    public $price;

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

    public function display() {
        return $this->name . " costs $" . $this->price;
    }
}

class Electronics extends Product {
    public $warranty;

    public function __construct($name, $price, $warranty) {
        parent::__construct($name, $price);
        $this->warranty = $warranty;
    }

    public function display() {
        return parent::display() . " and comes with a " . $this->warranty . "-year warranty.";
    }
}

$phone = new Electronics("Smartphone", 699, 2);
echo $phone->display(); // Output: Smartphone costs $699 and comes with a 2-year warranty.