MasterPHP.in
PHP Tutorial

Encapsulation & Polymorphism in php


In the previous lesson, you learned how to structure code using classes, constructors, and inheritance.

But there’s still a problem:

class BankAccount {
    public $balance = 1000;
}

$account = new BankAccount();
$account->balance = -5000; // Invalid value

πŸ‘‰ Anyone can change data directly β€” this breaks your logic.

Encapsulation and polymorphism solve this.


What is Encapsulation?

Encapsulation means restricting direct access to properties and controlling how data is modified.


Using Private Properties

class BankAccount {
    private $balance = 0;
}


$account = new BankAccount();
$account->balance = 5000;

Error:

Cannot access private property


Getter & Setter Methods

class BankAccount {
    private $balance = 0;

    public function setBalance($amount) {
        if ($amount >= 0) {
            $this->balance = $amount;
        }
    }

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

$account = new BankAccount();
$account->setBalance(5000);

echo $account->getBalance();

Output:

5000

πŸ‘‰ Getters use return instead of echo, so you can reuse the value anywhere.


private vs protected

class BankAccount {
    protected $balance = 1000;
}

class SavingsAccount extends BankAccount {
    public function addInterest() {
        $this->balance *= 1.05; // Allowed with protected
    }
}

πŸ‘‰ private β†’ accessible only inside the class

πŸ‘‰ protected β†’ accessible inside class + child classes


When to Use public, private, protected

  • Properties β†’ usually private
  • Methods β†’ public if accessed outside
  • Use protected when child classes need access


What is Polymorphism?

Polymorphism means same method name, different behavior.


Why Polymorphism Matters

Without Polymorphism

foreach ($animals as $animal) {
    if ($animal instanceof Dog) {
        echo "Bark";
    } elseif ($animal instanceof Cat) {
        echo "Meow";
    }
}

πŸ‘‰ Messy and hard to maintain.

With Polymorphism

class Animal {
    public function speak() {
        echo "Animal sound";
    }
}

class Dog extends Animal {
    public function speak() {
        echo "Bark";
    }
}

class Cat extends Animal {
    public function speak() {
        echo "Meow";
    }
}

$animals = [new Dog(), new Cat()];

foreach ($animals as $animal) {
    $animal->speak();
}

Output:

Bark
Meow

πŸ‘‰ Clean, scalable, and flexible.


Common Mistakes Beginners Make

1. Using Public Properties Everywhere

class User {
    public $email;
}

πŸ‘‰ Allows uncontrolled changes.

2. Forgetting Validation in Setters

public function setBalance($amount) {
    $this->balance = $amount;
}

πŸ‘‰ Allows invalid values.

Correct:

if ($amount >= 0)

3. Breaking Polymorphism with Wrong Access Level

class Dog extends Animal {
    private function speak() { // Wrong
        echo "Bark";
    }
}

πŸ‘‰ Child method must remain public to override correctly.


Practice Exercise

Task 1 (Easy)

Create a User class:

  • private property name
  • setter + getter
  • Create two users: "Rohan", "Amit"
  • Print both

Expected Output:

Rohan
Amit

Task 2 (Medium)

Create a Product class:

  • private price
  • setter (only allow > 0)
  • getter
  • Set price = 50000

Expected Output:

50000

Task 3 (Hard)

Create a base class Shape:

  • method area() β†’ prints "Shape area"

Create:

  • Circle β†’ override β†’ prints "Circle Area"
  • Square β†’ override β†’ prints "Square Area"

Loop through both objects and call area().

Expected Output:

Circle Area
Square Area


Summary

In this lesson, you learned:

  • encapsulation protects data using private
  • protected allows child class access
  • getters and setters control how data is modified
  • return gives flexibility over echo
  • polymorphism removes conditional logic
  • same method can behave differently across objects

Share this tutorial