KEMBAR78
PHP OOP Study Notes | PDF | Class (Computer Programming) | Object Oriented Programming
0% found this document useful (0 votes)
19 views55 pages

PHP OOP Study Notes

Uploaded by

nikh.sant123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views55 pages

PHP OOP Study Notes

Uploaded by

nikh.sant123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

What is OOP?

Concept Explanation
Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects—self-contained units
that combine data (properties/attributes) and behavior (methods/functions).
In PHP, OOP helps structure applications in a modular, reusable, and maintainable way.

Key principles of OOP:

Encapsulation → Protecting and grouping related data/methods.


Inheritance → Reusing code across hierarchies.
Polymorphism → One interface, many implementations.
Abstraction → Hiding complex details, exposing only essentials.

Beginner-Friendly Analogy
Think of a real-world car:

Properties → color, brand, model, fuel level.


Methods → drive(), brake(), refuel().

The car (object) bundles everything together.


Different cars share common structure but may behave differently.

PHP Code Example


<?php
// OOP Example: A simple Car class
class Car {
public $brand;
public $color;

public function drive() {


echo "The car is driving";
}
}

// Creating an object (instance of Car)


$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";

echo $car1->brand; // Output: Toyota


$car1->drive(); // Output: The car is driving
?>

Class and Object


Concept Explanation
A class in PHP is a blueprint/template that defines properties (variables) and methods (functions).
An object is an instance of a class, created in memory at runtime.
You can create many objects from the same class, each with its own values.

Beginner-Friendly Analogy
Think of a blueprint for a house:

The blueprint = class (design, reusable template).


Each constructed house = object (real instance with its own address, color, furniture).

PHP Code Example


<?php
// Defining a class
class Car {
public $brand;
public $color;

public function startEngine() {


echo "Engine started!";
}
}

// Creating objects (instances of Car)


$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";

$car2 = new Car();


$car2->brand = "Honda";
$car2->color = "Blue";

// Accessing object properties and methods


echo $car1->brand; // Output: Toyota
$car1->startEngine(); // Output: Engine started!

echo $car2->brand; // Output: Honda


$car2->startEngine(); // Output: Engine started!
?>

Properties and Methods


Concept Explanation
Properties are variables that belong to a class (they hold data).
Methods are functions defined inside a class (they define behavior).
Together, they represent the state (properties) and behavior (methods) of an object.

In PHP:

Properties are declared with visibility keywords (public, private, protected).


Methods are declared like regular functions but inside the class.
Beginner-Friendly Analogy
Think of a Smartphone:

Properties → brand, model, batteryLevel.


Methods → makeCall(), takePhoto(), playMusic().

The properties store information, and the methods define actions the phone can perform.

PHP Code Example


<?php
class Car {
// Properties (state/data)
public $brand;
public $color;

// Method (behavior)
public function drive() {
echo "The $this->color $this->brand is driving.";
}
}

// Creating an object and assigning values


$car = new Car();
$car->brand = "Tesla";
$car->color = "Black";

// Accessing properties and calling a method


echo $car->brand; // Output: Tesla
$car->drive(); // Output: The Black Tesla is driving.
?>

Constructor (__construct)
Concept Explanation
A constructor is a special method in PHP that runs automatically when an object is created.
It is defined using the __construct() method.
It is usually used to initialize properties or perform setup tasks when the object is instantiated.

Beginner-Friendly Analogy
Imagine moving into a new apartment:

The landlord gives you the keys and sets up the electricity/water when you arrive.
Similarly, a constructor automatically prepares the object with default or provided values.

PHP Code Example


<?php
class Car {
public $brand;
public $color;

// Constructor initializes properties


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

public function displayInfo() {


echo "Car: $this->brand, Color: $this->color";
}
}

// Creating an object with constructor


$car1 = new Car("BMW", "Blue");
$car1->displayInfo(); // Output: Car: BMW, Color: Blue

$car2 = new Car("Audi", "White");


$car2->displayInfo(); // Output: Car: Audi, Color: White
?>

The $this Keyword


Concept Explanation
In PHP, $this is a special variable available inside class methods.
It refers to the current object instance of the class.
It is used to access the object’s properties and methods within the class.

Beginner-Friendly Analogy
Think of “myself” in daily life:

If you say, “I am hungry”, the word “I” refers to yourself.


Similarly, $this is like an object saying “me”.
It allows the object to refer to its own properties and methods.

PHP Code Example


<?php
class Car {
public $brand;
public $color;

public function __construct($brand, $color) {


$this->brand = $brand; // refers to the current object's brand
$this->color = $color; // refers to the current object's color
}

public function displayInfo() {


echo "This car is a $this->color $this->brand.";
}
}

// Create object
$car = new Car("Tesla", "Red");
$car->displayInfo();
// Output: This car is a Red Tesla.
?>

Visibility (public, private,


protected)
Concept Explanation
Visibility (Access Modifiers) control how properties and methods can be accessed from inside or outside the
class.
PHP provides three levels of visibility:

1. public → Accessible from anywhere (inside class, outside class, subclasses).


2. private → Accessible only within the same class.
3. protected → Accessible within the same class and its subclasses (child classes).

This supports Encapsulation, keeping sensitive data safe while exposing only what’s needed.

Beginner-Friendly Analogy
Think of a house:

public → Front yard (anyone can see or access).


private → Bedroom (only you have access).
protected → Family room (you and family members can access, but not outsiders).

PHP Code Example


<?php
class BankAccount {
public $accountHolder; // Public: can be accessed anywhere
private $balance; // Private: only inside this class
protected $accountNumber; // Protected: this class + subclasses

public function __construct($holder, $balance, $accNum) {


$this->accountHolder = $holder;
$this->balance = $balance;
$this->accountNumber = $accNum;
}

// Public method can access private property


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

class SavingsAccount extends BankAccount {


public function getAccountNumber() {
// Can access protected property here
return $this->accountNumber;
}
}

$account = new BankAccount("Alice", 5000, "ACC123");

// Public property
echo $account->accountHolder; // Output: Alice

// Private property (will cause error if accessed directly)


// echo $account->balance;

echo $account->getBalance(); // Output: 5000

$savings = new SavingsAccount("Bob", 8000, "ACC456");


echo $savings->getAccountNumber(); // Output: ACC456
?>

Static Methods and Properties


Concept Explanation
Static properties and static methods belong to the class itself, not to an individual object.
They are accessed using the scope resolution operator ::.
You do not need to create an object to use them.
Static members are shared across all objects of the class.

Beginner-Friendly Analogy
Think of a school:

Static property = school name (same for all students).


Object property = student’s name (unique for each student).

PHP Code Example


<?php
class MathHelper {
// Static property
public static $pi = 3.14159;

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

// Access static property


echo MathHelper::$pi; // Output: 3.14159

// Call static method


echo MathHelper::add(10, 20); // Output: 30

// You don't need to create an object


// $math = new MathHelper(); Not required
?>

Object vs Class Context


Concept Explanation
In PHP OOP, code can run in either:
1. Object Context → Using an instance (object) of a class.
Accessed with $this.
Works with non-static properties/methods.
2. Class Context → Using the class itself, without creating an object.
Accessed with ClassName::method() or ClassName::$property.
Works with static properties/methods.

Understanding the difference helps avoid errors like using $this inside a static method.

Beginner-Friendly Analogy
Think of a University:

Object Context = individual student (unique name, roll number).


Class Context = the university itself (same motto, same rules for everyone).

PHP Code Example


<?php
class Student {
public $name; // Object property
public static $school = "ABC University"; // Class property

public function __construct($name) {


$this->name = $name; // Object context
}

public function showName() {


echo "Student Name: " . $this->name; // Instance-specific
}

public static function showSchool() {


echo "School: " . self::$school; // Class-specific
}
}

// Object context
$student1 = new Student("Alice");
$student1->showName(); // Student Name: Alice

// Class context (no object needed)


Student::showSchool(); // School: ABC University
?>

Encapsulation
Concept Explanation
Encapsulation means wrapping data (properties) and behavior (methods) inside a single unit (class).
It also restricts direct access to certain data by using access modifiers (private, protected).
Instead, data is accessed through getter and setter methods (controlled access).
This improves security, data integrity, and code maintainability.

Beginner-Friendly Analogy
Think of a capsule medicine :

The capsule hides the powder inside.


You don’t directly touch the raw medicine; you consume it safely.
Similarly, encapsulation hides internal details and provides safe access through methods.

PHP Code Example


<?php
class BankAccount {
private $balance; // Private: cannot be accessed directly

public function __construct($initialBalance) {


$this->balance = $initialBalance;
}

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

// Setter method
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
}
}

public function withdraw($amount) {


if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
}
}
}

$account = new BankAccount(1000);


// Direct access: echo $account->balance;

$account->deposit(500);
$account->withdraw(200);

echo $account->getBalance(); // Output: 1300


?>
Inheritance
Concept Explanation
Inheritance allows one class (child/derived) to reuse and extend the properties and methods of another class
(parent/base).
Promotes code reusability and hierarchical relationships between classes.
In PHP, inheritance is achieved using the extends keyword.

Beginner-Friendly Analogy
Think of a family tree :

A child inherits features (like eye color, surname) from their parents.
Similarly, in programming, a subclass inherits properties/methods from its parent class.

PHP Code Example


<?php
// Parent class
class Vehicle {
public $brand;

public function __construct($brand) {


$this->brand = $brand;
}

public function startEngine() {


echo "$this->brand engine started.\n";
}
}

// Child class (inherits from Vehicle)


class Car extends Vehicle {
public $model;

public function __construct($brand, $model) {


parent::__construct($brand); // Call parent constructor
$this->model = $model;
}

public function showDetails() {


echo "Car: $this->brand $this->model\n";
}
}

$car = new Car("Tesla", "Model S");


$car->startEngine(); // Tesla engine started.
$car->showDetails(); // Car: Tesla Model S
?>

Method Overriding
Concept Explanation
Method Overriding happens when a child class provides a new implementation of a method that already exists
in the parent class.
The method in the child class must have the same name and parameters as in the parent.
It allows a subclass to modify or extend the behavior of its parent’s methods.
Beginner-Friendly Analogy
Think of a default phone ringtone :

Every phone model comes with a default ringtone (parent class method).
But you can override it with your custom ringtone (child class method).

PHP Code Example


<?php
class Animal {
public function makeSound() {
echo "Some generic animal sound\n";
}
}

class Dog extends Animal {


// Overriding parent method
public function makeSound() {
echo "Bark! Bark!\n";
}
}

class Cat extends Animal {


// Overriding parent method
public function makeSound() {
echo "Meow!\n";
}
}

$animal = new Animal();


$animal->makeSound(); // Some generic animal sound

$dog = new Dog();


$dog->makeSound(); // Bark! Bark!

$cat = new Cat();


$cat->makeSound(); // Meow!
?>
Interfaces
Concept Explanation
An interface in PHP defines a contract (set of methods) that a class must implement.
Interfaces only declare method signatures (no implementation).
A class can implement multiple interfaces (helps achieve multiple inheritance-like behavior).
Declared with the interface keyword and implemented using the implements keyword.

Beginner-Friendly Analogy
Think of a remote control interface :

The interface defines which buttons (methods) must exist: power, volume, channel.
Different brands (classes) implement the remote differently, but they must all follow the same rules.

PHP Code Example


<?php
interface PaymentGateway {
public function pay($amount);
}

class PayPal implements PaymentGateway {


public function pay($amount) {
echo "Paying $amount via PayPal.\n";
}
}

class Stripe implements PaymentGateway {


public function pay($amount) {
echo "Paying $amount via Stripe.\n";
}
}

function processPayment(PaymentGateway $gateway, $amount) {


$gateway->pay($amount);
}

processPayment(new PayPal(), 100); // Paying 100 via PayPal.


processPayment(new Stripe(), 200); // Paying 200 via Stripe.
?>

Final Keyword
Concept Explanation
The final keyword in PHP is used to restrict inheritance or method overriding.
It can be applied in two ways:
1. Final class → cannot be inherited.
2. Final method → cannot be overridden in child classes.
Helps enforce rules and prevent unintended changes in critical parts of code.

Beginner-Friendly Analogy
Think of a sealed jar :

Once sealed (final), you cannot open it to change what’s inside.


Similarly, a final class or method cannot be extended or modified further.

PHP Code Example


<?php
// Final class example
final class DatabaseConnection {
public function connect() {
echo "Connecting to the database...\n";
}
}

// Error: Cannot extend a final class


// class MySQLConnection extends DatabaseConnection {}

// Final method example


class Vehicle {
final public function startEngine() {
echo "Engine started.\n";
}
}

class Car extends Vehicle {


// Error: Cannot override a final method
// public function startEngine() {
// echo "Car engine started.\n";
// }
}
?>

Traits
Concept Explanation
Traits in PHP are a mechanism for code reuse.
They allow you to include methods in multiple classes without using inheritance.
Unlike classes, a trait cannot be instantiated on its own.
Declared with the trait keyword and used with the use keyword inside a class.
Helps overcome PHP’s single inheritance limitation.
Beginner-Friendly Analogy
Think of stickers :

You can apply the same sticker (trait) to different objects (classes).
Each object still keeps its own identity, but gains the additional sticker functionality.

PHP Code Example


<?php
trait Logger {
public function log($message) {
echo "[LOG]: $message\n";
}
}

trait FileHandler {
public function saveToFile($filename, $data) {
file_put_contents($filename, $data);
echo "Data saved to $filename\n";
}
}

class User {
use Logger, FileHandler; // Include traits

public function createUser($name) {


$this->log("Creating user: $name");
$this->saveToFile("users.txt", $name);
}
}

$user = new User();


$user->createUser("Alice");
// Output:
// [LOG]: Creating user: Alice
// Data saved to users.txt
?>
Abstract Classes and
Methods
Concept Explanation
An abstract class in PHP is a class that cannot be instantiated directly.
It may contain abstract methods (declared but not implemented) and concrete methods (fully defined).
Abstract methods must be implemented by any class that extends the abstract class.
Declared with the abstract keyword.

Beginner-Friendly Analogy
Think of an architect’s blueprint :

You can’t live in the blueprint (abstract class).


The blueprint defines what a house must have (abstract methods), but the builder (subclass) decides how to build
it.

PHP Code Example


<?php
// Abstract class
abstract class Animal {
// Abstract method (must be implemented in child class)
abstract public function makeSound();

// Concrete method (can be used as-is)


public function sleep() {
echo "Sleeping...\n";
}
}

class Dog extends Animal {


public function makeSound() {
echo "Bark!\n";
}
}

class Cat extends Animal {


public function makeSound() {
echo "Meow!\n";
}
}

// $animal = new Animal(); Error: Cannot instantiate abstract class

$dog = new Dog();


$dog->makeSound(); // Bark!
$dog->sleep(); // Sleeping...

$cat = new Cat();


$cat->makeSound(); // Meow!
?>

Polymorphism
Concept Explanation
Polymorphism means “many forms” in OOP.
It allows different classes to define methods with the same name but with different behaviors.
In PHP, polymorphism is mainly achieved through inheritance and interfaces.
It helps write flexible and reusable code by treating objects of different types uniformly.

Beginner-Friendly Analogy
Think of the word “drive” :

A person drives a car.


A pilot drives (flies) a plane.
A sailor drives (sails) a ship.
The action is named the same (drive), but its meaning changes depending on the context (object).

PHP Code Example


<?php
interface Animal {
public function makeSound();
}

class Dog implements Animal {


public function makeSound() {
echo "Bark!\n";
}
}

class Cat implements Animal {


public function makeSound() {
echo "Meow!\n";
}
}

class Cow implements Animal {


public function makeSound() {
echo "Moo!\n";
}
}

// Polymorphism in action
$animals = [new Dog(), new Cat(), new Cow()];

foreach ($animals as $animal) {


$animal->makeSound();
}
// Output:
// Bark!
// Meow!
// Moo!
?>

Type Hinting
Concept Explanation
Type Hinting in PHP allows you to specify the expected data type for function parameters and return values.
Introduced in PHP 7 and improved in later versions.
Ensures code reliability by enforcing that only the correct data type is passed.
Supported types include:
Scalar types (int, string, bool, float)
Class types (specific objects)
array, callable, iterable, object, mixed, ?type (nullable types)
Helps reduce bugs and makes code self-documenting.

Beginner-Friendly Analogy
Imagine a mailbox :

A mailbox is designed to accept letters only.


If someone tries to put in a basketball, it won’t fit.
Similarly, type hinting ensures only the expected type can be passed into a function.

PHP Code Example


<?php
class User {
public $name;

public function __construct(string $name) {


$this->name = $name;
}
}

function greetUser(User $user): string { // Type hinting parameter & return


return "Hello, " . $user->name;
}

$user = new User("Alice");


echo greetUser($user);
// Output: Hello, Alice

// greetUser("Bob"); Error: Argument must be an instance of User


?>

Dependency Injection
Concept Explanation
Dependency Injection (DI) is a design pattern where an object’s dependencies are provided externally, rather
than the object creating them itself.
Promotes loose coupling and makes code more testable, reusable, and maintainable.
In PHP, DI is often used with constructors, setters, or through framework service containers.

Beginner-Friendly Analogy
Think of a car and its fuel :

Instead of the car producing its own fuel, the fuel is injected from outside at a gas station.
Similarly, objects should not create their own dependencies but instead receive them from the outside.

PHP Code Example


<?php
// Dependency: Engine
class Engine {
public function start() {
echo "Engine started...\n";
}
}

// Dependent class: Car


class Car {
private $engine;

// Dependency is injected via constructor


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

public function drive() {


$this->engine->start();
echo "Car is moving...\n";
}
}

// Inject dependency
$engine = new Engine();
$car = new Car($engine);
$car->drive();
// Output:
// Engine started...
// Car is moving...
?>

Namespaces
Concept Explanation
Namespaces in PHP are used to organize code and avoid name conflicts between classes, functions, and
constants.
Declared with the namespace keyword at the top of a PHP file.
They act like folders for your code.
You can import namespaces with the use keyword.
Beginner-Friendly Analogy
Imagine a library :

Two books may have the same title, but they belong to different sections (Science, Literature, History).
Similarly, two PHP classes can have the same name but live in different namespaces.

PHP Code Example


<?php
// File: Animals/Dog.php
namespace Animals;

class Dog {
public function bark() {
echo "Woof!\n";
}
}
?>

<?php
// File: Pets/Dog.php
namespace Pets;

class Dog {
public function bark() {
echo "Bow-wow!\n";
}
}
?>

<?php
// Main file
require "Animals/Dog.php";
require "Pets/Dog.php";

use Animals\Dog as WildDog;


use Pets\Dog as PetDog;

$dog1 = new WildDog();


$dog1->bark(); // Woof!

$dog2 = new PetDog();


$dog2->bark(); // Bow-wow!
?>

Autoloading
Concept Explanation
Autoloading in PHP is a mechanism to automatically load required class files without manually including them
using require or include.
Implemented via:
1. spl_autoload_register() – register a custom autoload function.
2. Composer Autoloader – widely used in modern PHP projects.
Helps in organizing large projects and keeps code cleaner.

Beginner-Friendly Analogy
Think of a Netflix subscription :

You don’t have to download every movie beforehand.


When you select a movie, Netflix automatically fetches it for you.
Similarly, PHP autoloading fetches the class file only when it’s needed.

PHP Code Example


<?php
// Autoloader using spl_autoload_register
spl_autoload_register(function ($className) {
include $className . '.php'; // assumes file name = class name
});

// Dog.php
class Dog {
public function bark() {
echo "Woof!\n";
}
}

// Cat.php
class Cat {
public function meow() {
echo "Meow!\n";
}
}

// No need to require files manually


$dog = new Dog();
$dog->bark(); // Woof!

$cat = new Cat();


$cat->meow(); // Meow!
?>

Magic Methods (__get, __set,


__call)
Concept Explanation
PHP provides Magic Methods that start with double underscores (__).
They are automatically triggered when certain actions are performed on objects.
Commonly used magic methods:
__get($property) → Triggered when accessing an undefined or inaccessible property.
__set($property, $value) → Triggered when assigning a value to an undefined or inaccessible
property.
__call($method, $arguments) → Triggered when calling an undefined or inaccessible method.
They help in creating dynamic and flexible objects.

Beginner-Friendly Analogy
Imagine a hotel receptionist :

If you ask for a service that isn’t directly available, the receptionist tries to fetch it for you.
Similarly, magic methods catch requests for undefined properties/methods and handle them gracefully.

PHP Code Example


<?php
class Student {
private $data = [];

// Handle setting undefined property


public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}

// Handle getting undefined property


public function __get($name) {
if (isset($this->data[$name])) {
return $this->data[$name];
}
return "Property '$name' not found.\n";
}

// Handle calling undefined method


public function __call($name, $arguments) {
echo "Method '$name' not found. Arguments: " . implode(", ", $arguments) . "\n";
}
}

$student = new Student();

// __set triggered
$student->age = 21;

// __get triggered
echo $student->age . "\n";

// __call triggered
$student->study("Math", "Science");
?>

__construct and __destruct


Concept Explanation
__construct() is a constructor method in PHP:
Automatically called when an object is created.
Used to initialize properties or inject dependencies.
__destruct() is a destructor method:
Automatically called when an object is destroyed (end of script or unset).
Used for cleanup (closing files, database connections, etc.).

Beginner-Friendly Analogy
Think of a hotel stay :

When you check in, the receptionist prepares everything you need → __construct().
When you check out, the hotel staff clears the room and finalizes the bill → __destruct().

PHP Code Example


<?php
class FileHandler {
private $file;

// Constructor: open file when object is created


public function __construct($filename) {
$this->file = fopen($filename, "w");
echo "File opened.\n";
}

public function write($content) {


fwrite($this->file, $content);
}

// Destructor: close file when object is destroyed


public function __destruct() {
fclose($this->file);
echo "File closed.\n";
}
}

$handler = new FileHandler("example.txt");


$handler->write("Hello, PHP OOP!\n");

// Destructor will be automatically called at the end


?>
instanceof and Type Checking
Concept Explanation
instanceof is an operator in PHP that checks if an object belongs to a specific class (or subclass).
Useful for type checking in OOP.
Helps ensure methods receive the right type of object before executing operations.

Beginner-Friendly Analogy
Imagine a zoo :

You check if an animal is a Lion before putting it in the lion cage.


Similarly, in PHP you use instanceof to check if an object is of a particular class.

PHP Code Example


<?php
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

$dog = new Dog();


$cat = new Cat();

// Check type
if ($dog instanceof Dog) {
echo "Yes, this is a Dog.\n";
}

if ($cat instanceof Animal) {


echo "Yes, Cat is an Animal.\n";
}

if (!($dog instanceof Cat)) {


echo "Dog is not a Cat.\n";
}
?>
Late Static Binding
Concept Explanation
Late Static Binding (LSB) in PHP solves a problem with inheritance and self::.
When using self::, PHP refers to the class where the method is defined, not where it’s called.
With late static binding, static:: is used instead of self::, and it refers to the class that was actually
called at runtime.
This allows child classes to override behavior dynamically.

Beginner-Friendly Analogy
Think of a family recipe :

If you always refer to self::, you’re stuck with the recipe written by the parent (no customization).
If you use static::, it means the current chef (child class) can tweak the recipe while keeping the base idea.

PHP Code Example


<?php
class ParentClass {
public static function who() {
echo "I am ParentClass\n";
}

public static function test() {


// self:: refers to the class where this is defined (ParentClass)
self::who();

// static:: refers to the class that actually called the method


static::who();
}
}

class ChildClass extends ParentClass {


public static function who() {
echo "I am ChildClass\n";
}
}

ChildClass::test();
?>

Static Binding vs Dynamic


Binding
Concept Explanation
Static Binding:

Function/method calls are resolved at compile time (before execution).


Uses self:: or parent::.
Always binds to the class where the method is defined.

Dynamic Binding:

Function/method calls are resolved at runtime (during execution).


Uses static:: (late static binding) or polymorphism.
Depends on the object’s actual type at runtime.

Beginner-Friendly Analogy
Imagine calling a helpline number ☎:

Static Binding → You always get redirected to the head office (no matter who called).
Dynamic Binding → You get connected to the nearest local branch (depends on who’s calling).

PHP Code Example


<?php
class ParentClass {
public static function who() {
echo "I am ParentClass\n";
}

public static function test() {


// Static Binding
self::who();

// Dynamic Binding (Late Static Binding)


static::who();
}
}

class ChildClass extends ParentClass {


public static function who() {
echo "I am ChildClass\n";
}
}

ChildClass::test();
?>

Object Cloning (__clone())


Concept Explanation
In PHP, assigning one object to another ($obj2 = $obj1) does not create a copy.
Both variables point to the same object in memory.
To create a copy of an object, you use the clone keyword.
When cloning:
PHP creates a shallow copy of the object by default.
You can define the __clone() magic method to customize cloning behavior.

Beginner-Friendly Analogy
Think of photocopying a document :

A simple clone is like making a photocopy → it looks the same but is a different sheet.
If the document has attachments (nested objects), a shallow copy doesn’t duplicate them—it just points to the
same attachments.

PHP Code Example


<?php
class Student {
public $name;
public $subject;

public function __construct($name, $subject) {


$this->name = $name;
$this->subject = $subject;
}

// Custom cloning behavior


public function __clone() {
echo "Cloning object...\n";
}
}

$student1 = new Student("Alice", "Math");

// Clone the object


$student2 = clone $student1;

$student2->name = "Bob";

echo $student1->name . " studies " . $student1->subject . "\n";


echo $student2->name . " studies " . $student2->subject . "\n";
?>

Deep Copy vs Shallow Copy


Concept Explanation
Shallow Copy:

Duplicates only the top-level object.


Nested objects or references inside it are not cloned, they still point to the same memory.
Default behavior of clone in PHP.

Deep Copy:

Duplicates the object and all nested objects/references inside it.


Requires custom logic inside __clone() to recursively clone referenced objects.
Beginner-Friendly Analogy
Imagine copying a notebook :

Shallow Copy: You photocopy the notebook cover and pages, but sticky notes inside still belong to the original
notebook.
Deep Copy: You photocopy the entire notebook including every sticky note and attachment—a complete
independent duplicate.

PHP Code Example


<?php
class Subject {
public $title;
public function __construct($title) {
$this->title = $title;
}
}

class Student {
public $name;
public $subject;

public function __construct($name, Subject $subject) {


$this->name = $name;
$this->subject = $subject;
}

// Deep copy implementation


public function __clone() {
$this->subject = clone $this->subject;
}
}

// Shallow copy
$student1 = new Student("Alice", new Subject("Math"));
$student2 = clone $student1; // Deep copy due to __clone()

$student2->name = "Bob";
$student2->subject->title = "Science";

echo $student1->name . " studies " . $student1->subject->title . "\n";


echo $student2->name . " studies " . $student2->subject->title . "\n";
?>

Composition (Has-A
Relationship)
Concept Explanation
Composition means building a class using other classes as components.

Instead of inheritance (is-a relationship), composition represents a has-a relationship.

Example:

A Car has-a Engine.


A Computer has-a CPU.

Promotes code reuse without forcing strict inheritance hierarchies.

Beginner-Friendly Analogy
Think of a house :

A house is not a kitchen, but it has a kitchen.


Similarly, in PHP, instead of saying a House extends Kitchen, we say House has a Kitchen object inside it.

PHP Code Example


<?php
class Engine {
public function start() {
echo "Engine started...\n";
}
}

class Car {
private $engine;

public function __construct() {


// Composition: Car has an Engine
$this->engine = new Engine();
}

public function drive() {


$this->engine->start();
echo "Car is driving...\n";
}
}

$car = new Car();


$car->drive();
?>

Singleton Pattern
Concept Explanation
The Singleton Pattern ensures that only one instance of a class exists throughout the application.
Provides a global access point to that instance.
Useful for managing shared resources like database connections, logging, or configuration settings.

Beginner-Friendly Analogy
Think of a president of a country :

There can only be one president at a time.


Everyone refers to the same person for leadership.
Similarly, in PHP, a Singleton ensures only one instance of a class exists.
PHP Code Example
<?php
class Database {
private static $instance = null;
private $connection;

// Private constructor prevents direct instantiation


private function __construct() {
$this->connection = "Connected to Database";
}

// Get the single instance


public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Database();
}
return self::$instance;
}

public function getConnection() {


return $this->connection;
}
}

// Usage
$db1 = Database::getInstance();
$db2 = Database::getInstance();

// Both variables hold the SAME instance


echo $db1->getConnection() . "\n";
echo ($db1 === $db2) ? "Same instance\n" : "Different instances\n";
?>

SOLID Principles in PHP


The SOLID principles are five design principles that make software:

More maintainable
Easier to extend
Less prone to bugs
Highly reusable

We’ll go through them one by one.

S → Single Responsibility Principle (SRP)


Concept Explanation
A class should have only one reason to change.
In other words, each class should be responsible for only one job.
Prevents classes from becoming “God classes” that handle too many responsibilities.

Beginner-Friendly Analogy
Think of a restaurant worker :

A chef cooks food.


A waiter serves customers.
If one person tries to do both jobs, they get overworked and confused.
Similarly, in code, each class should focus on one responsibility.

PHP Code Example


<?php
// Violates SRP: One class doing multiple things
class User {
public function getUserData() {
return "User Data";
}

public function saveToFile($data) {


file_put_contents("user.txt", $data);
}
}

// Follows SRP: Separate responsibilities


class User {
public function getUserData() {
return "User Data";
}
}

class UserRepository {
public function save(User $user) {
file_put_contents("user.txt", $user->getUserData());
}
}

// Usage
$user = new User();
$repo = new UserRepository();
$repo->save($user);
?>

O → Open/Closed Principle
(OCP)
Concept Explanation
A class should be open for extension but closed for modification.
Meaning: You should be able to add new functionality without changing existing code.
Achieved using inheritance, interfaces, or composition.
Prevents breaking existing code when requirements change.

Beginner-Friendly Analogy
Think of a power strip (extension board) :

You can plug in new devices (extend functionality).


You don’t need to open the power strip and rewire it (modify the internals).
Similarly, software should allow adding new features without modifying tested code.

PHP Code Example


<?php
// Violates OCP: Adding payment methods requires modifying this class
class Payment {
public function pay($type) {
if ($type == "credit") {
echo "Paid with Credit Card\n";
} elseif ($type == "paypal") {
echo "Paid with PayPal\n";
}
}
}

// Follows OCP: Open for extension, closed for modification


interface PaymentMethod {
public function pay();
}

class CreditCardPayment implements PaymentMethod {


public function pay() {
echo "Paid with Credit Card\n";
}
}

class PayPalPayment implements PaymentMethod {


public function pay() {
echo "Paid with PayPal\n";
}
}

class PaymentProcessor {
public function process(PaymentMethod $method) {
$method->pay();
}
}

// Usage
$processor = new PaymentProcessor();
$processor->process(new CreditCardPayment());
$processor->process(new PayPalPayment());
?>
L → Liskov Substitution
Principle (LSP)
Concept Explanation
Definition: Objects of a superclass should be replaceable with objects of a subclass without breaking the
program.
In other words: A child class should behave like its parent class without unexpected side effects.
Ensures correct inheritance and prevents misuse of polymorphism.

Beginner-Friendly Analogy
Think of a bird :

If Bird has a method fly(), then all subclasses (like Sparrow, Pigeon) should also be able to fly.
But if we create a Penguin subclass, it cannot fly → this violates LSP.
So, design carefully to avoid such broken hierarchies.

PHP Code Example


<?php
// Violates LSP
class Bird {
public function fly() {
echo "Flying...\n";
}
}

class Penguin extends Bird {


// Penguins cannot fly, so overriding breaks expectations
public function fly() {
throw new Exception("Penguins can't fly!");
}
}

// Follows LSP: Proper abstraction


interface Bird {
public function eat();
}

interface FlyableBird extends Bird {


public function fly();
}

class Sparrow implements FlyableBird {


public function eat() {
echo "Sparrow is eating\n";
}
public function fly() {
echo "Sparrow is flying\n";
}
}

class Penguin implements Bird {


public function eat() {
echo "Penguin is eating\n";
}
}

// Usage
$sparrow = new Sparrow();
$sparrow->fly(); // Works fine
$penguin = new Penguin();
$penguin->eat(); // No fly() expected
?>

I → Interface Segregation
Principle (ISP)
Concept Explanation
Clients (classes) should not be forced to implement methods they do not use.
Instead of one large, “fat” interface, create multiple smaller, specific interfaces.
Promotes loose coupling and cleaner design.

Beginner-Friendly Analogy
Imagine a Swiss Army Knife :

It has scissors, knife, corkscrew, saw, and more.


If you just want to cut vegetables, all those extra tools are unnecessary baggage.
Instead, having a simple kitchen knife interface is better.
Similarly, classes should only depend on what they actually need.

PHP Code Example


<?php
// Violates ISP: Interface forces all animals to implement fly()
interface Animal {
public function eat();
public function fly();
}

class Dog implements Animal {


public function eat() {
echo "Dog is eating\n";
}
public function fly() {
// Dogs cannot fly, so this method is useless
throw new Exception("Dogs can't fly!");
}
}

// Follows ISP: Split into smaller interfaces


interface Eater {
public function eat();
}

interface Flyer {
public function fly();
}

class Sparrow implements Eater, Flyer {


public function eat() {
echo "Sparrow is eating\n";
}
public function fly() {
echo "Sparrow is flying\n";
}
}

class Dog2 implements Eater {


public function eat() {
echo "Dog is eating\n";
}
}

// Usage
$sparrow = new Sparrow();
$sparrow->fly();

$dog = new Dog2();


$dog->eat();
?>

D → Dependency Inversion
Principle (DIP)
Concept Explanation
High-level modules should not depend on low-level modules.
Both should depend on abstractions (interfaces).
Abstractions should not depend on details, but details should depend on abstractions.
This makes systems flexible, testable, and decoupled.

Beginner-Friendly Analogy
Think of a universal remote control :

The TV remote doesn’t care whether it controls a Sony TV or a Samsung TV.


It just sends commands (abstractions).
Each TV brand implements those commands in its own way.
Similarly, high-level code should depend on interfaces, not concrete implementations.

PHP Code Example


<?php
// Violates DIP: High-level class depends directly on a low-level class
class MySQLDatabase {
public function connect() {
return "Connected to MySQL Database\n";
}
}

class UserRepository {
private $db;

public function __construct() {


$this->db = new MySQLDatabase(); // Tight coupling
}

public function getUser() {


echo $this->db->connect();
echo "Fetching user...\n";
}
}

// Follows DIP: Depend on abstractions


interface Database {
public function connect();
}

class MySQLDatabase2 implements Database {


public function connect() {
return "Connected to MySQL Database\n";
}
}

class PostgreSQLDatabase implements Database {


public function connect() {
return "Connected to PostgreSQL Database\n";
}
}

class UserRepository2 {
private $db;

// Dependency is injected via constructor


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

public function getUser() {


echo $this->db->connect();
echo "Fetching user...\n";
}
}

// Usage
$repo1 = new UserRepository2(new MySQLDatabase2());
$repo1->getUser();

$repo2 = new UserRepository2(new PostgreSQLDatabase());


$repo2->getUser();
?>

You might also like