Object-Oriented Programming (OOP) in PHP
 in PHP.jpg)
Object-Oriented Programming (OOP) in PHP
PHP supports Object-Oriented Programming (OOP), which helps in writing modular, reusable, and organized code.
1. Classes and Objects
A class is a blueprint for creating objects.
An object is an instance of a class.
✅ Example: Defining a Class & Creating an Object
<?php
class Car {
public $brand; // Property
// Method
public function setBrand($brand) {
$this->brand = $brand;
}
public function getBrand() {
return $this->brand;
}
}
// Creating an object of the Car class
$car1 = new Car();
$car1->setBrand("Toyota");
echo "Car Brand: " . $car1->getBrand();
?>
<?php
class User {
public $name; // Can be accessed anywhere
private $password; // Only accessible inside the class
public function setPassword($password) {
$this->password = $password;
}
public function getPassword() {
return $this->password; // Allowed inside class
}
}
$user1 = new User();
$user1->name = "Alice";
$user1->setPassword("secret123");
// Accessing public property
echo "User: " . $user1->name . "
";
// Accessing private property via a method
echo "Password: " . $user1->getPassword();
?>
<?php
class Animal {
public $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
// Dog inherits from Animal
class Dog extends Animal {
public function bark() {
return "Woof! Woof!";
}
}
$dog = new Dog();
$dog->setName("Buddy");
echo $dog->getName() . " says " . $dog->bark();
?>
<?php
class Shape {
public function draw() {
return "Drawing a shape";
}
}
class Circle extends Shape {
public function draw() {
return "Drawing a Circle";
}
}
$shape = new Shape();
echo $shape->draw() . "
"; // Output: Drawing a shape
$circle = new Circle();
echo $circle->draw(); // Output: Drawing a Circle
?>
<?php
class BankAccount {
private $balance = 0;
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}
public function getBalance() {
return $this->balance;
}
}
$account = new BankAccount();
$account->deposit(100);
echo "Balance: $" . $account->getBalance();
?>
<?php
class Person {
public $name;
public function __construct($name) {
$this->name = $name;
echo "Object created: " . $this->name . "
";
}
public function __destruct() {
echo "Object destroyed: " . $this->name . "
";
}
}
$person1 = new Person("Alice");
?>
<?php
namespace Library;
class Book {
public function info() {
return "This is a book";
}
}
?>
<?php
include 'Library.php';
use Library\Book;
$book = new Book();
echo $book->info();
?>
Date: 2025-03-28 00:00:00.000000