Object-Oriented Programming (OOP) in PHP helps structure code using real-world concepts. It improves readability, scalability, and maintainability of applications.
A class acts as a blueprint, while an object is an instance of that class. Constructors initialize data, and methods define behavior.
// 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();
?>
// 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();
?>
The output displays descriptive text showing how objects use inherited properties and methods.
Try changing class properties or adding new methods to see how objects behave differently.
__construct() for initializationprivate or protected propertiesStudent class with name and gradeCollegeStudent with collegeName