← Back to Chapters

PHP OOP Introduction

? PHP OOP Introduction

✨ Quick Overview

Object-Oriented Programming (OOP) in PHP helps structure code using real-world concepts. It improves readability, scalability, and maintainability of applications.

? Key Concepts

  • Class
  • Object
  • Properties
  • Methods
  • Constructor
  • Inheritance
  • Polymorphism

? Syntax & Theory

A class acts as a blueprint, while an object is an instance of that class. Constructors initialize data, and methods define behavior.

? Basic Class & Object

? View Code Example
// Defining a Car class with property and method
<?php
class Car {
public $brand;

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

public function drive() {
return "Driving a " . $this->brand;
}
}

$car1 = new Car("Toyota");
echo $car1->drive();
?>

?️ Inheritance Example

? View Code Example
// Demonstrating inheritance using Vehicle and Bike classes
<?php
class Vehicle {
public $type;
public function __construct($type) {
$this->type = $type;
}
}

class Bike extends Vehicle {
public $brand;
public function __construct($brand) {
parent::__construct("Two Wheeler");
$this->brand = $brand;
}

public function showInfo() {
return $this->brand . " is a " . $this->type;
}
}

$bike = new Bike("Royal Enfield");
echo $bike->showInfo();
?>

? Live Output / Explanation

The output displays descriptive text showing how objects use inherited properties and methods.

? Interactive Concept

Try changing class properties or adding new methods to see how objects behave differently.

?️ Use Cases

  • Web applications with complex data models
  • Reusable libraries and frameworks
  • Large-scale enterprise systems

✅ Tips & Best Practices

  • Use __construct() for initialization
  • Prefer private or protected properties
  • Keep one responsibility per class

? Try It Yourself

  • Create a Student class with name and grade
  • Extend it into CollegeStudent with collegeName
  • Display details using a method