Access Modifiers and Encapsulation in PHP Practice Questions with Solutions

Introduction

In PHP, access modifiers control where class properties and methods can be accessed. Encapsulation means keeping data protected inside a class and allowing access through controlled methods. In this chapter, you will learn public, private and protected access modifiers and how to use encapsulation through practical PHP examples. Access Modifiers and Encapsulation in PHP Practice questions with Solutions to help you to understand the concepts.

Understanding Access Modifiers in PHP

PHP provides three main access modifiers:

1. Public

A public property or method can be accessed from anywhere: inside the class, outside the class and from child classes.

<?php

class Student
{
    public $name = "Rahul";
}

$student = new Student();

echo $student->name;

?>

Output:

Rahul

Here, $name is public, so it can be accessed directly using the object.

2. Private

A private property or method can only be accessed inside the class where it is declared. It cannot be accessed directly from outside the class or from child classes.

<?php

class Student
{
    private $marks = 90;

    public function displayMarks()
    {
        echo $this->marks;
    }
}

$student = new Student();

$student->displayMarks();

?>

Output:

90

The marks property is private. The public displayMarks() method provides controlled access to it.

3. Protected

A protected property or method can be accessed inside its own class and its child classes. It cannot be accessed directly from outside the class.

<?php

class Student
{
    protected $course = "PHP";
}

class AdvancedStudent extends Student
{
    public function displayCourse()
    {
        echo $this->course;
    }
}

$student = new AdvancedStudent();

$student->displayCourse();

?>

Output:

PHP

The child class can access the protected property inherited from its parent class.

Difference Between Public, Private and Protected

Access ModifierInside Own ClassOutside ClassChild Class
PublicYesYesYes
PrivateYesNoNo
ProtectedYesNoYes

Understanding Encapsulation in PHP

Encapsulation means keeping the internal data of a class protected and controlling how that data is accessed or changed.

For example, imagine a bank account. Anyone should not be able to directly change its balance. Instead, the class should provide methods such as deposit() and withdraw() to manage the balance.

A common encapsulation pattern is:

  1. Declare properties as private.
  2. Create public methods to read or update those properties.
  3. Validate values before changing important data.
  4. Keep the object’s data in a valid state.

Simple Example:

<?php

class BankAccount
{
    private $balance = 10000;

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

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

$account = new BankAccount();

$account->deposit(2000);

echo $account->getBalance();

?>

Output:

12000

Here, the balance cannot be accessed directly from outside the class. The public methods control how the balance is read and updated.

Question 1: Create a Class with Public Properties

Problem Statement

Create a Student class with public properties name, rollNumber and course. Create an object and access all three properties directly.

PHP Solution

<?php

class Student
{
    public $name = "Rahul";
    public $rollNumber = 101;
    public $course = "PHP";
}

$student = new Student();

echo "Student Name: " . $student->name . "<br>";
echo "Roll Number: " . $student->rollNumber . "<br>";
echo "Course: " . $student->course;

?>

Sample Output

Student Name: Rahul
Roll Number: 101
Course: PHP

Explanation

  • The Student class contains three public properties.
  • The public keyword allows these properties to be accessed outside the class.
  • The $student object is created using the new keyword.
  • Each property is accessed using the object operator ->.

Because all properties are public, you can read and update them directly.

Concepts Covered

  • Public access modifier
  • Public properties
  • Object property access
  • Object creation

Question 2: Create a Class with Private Properties

Problem Statement

Create an Employee class with private properties name and salary. Create a public method called displayDetails() to display their values.

PHP Solution

<?php

class Employee
{
    private $name = "Amit";
    private $salary = 35000;

    public function displayDetails()
    {
        echo "Employee Name: " . $this->name . "<br>";
        echo "Salary: Rs. " . $this->salary;
    }
}

$employee = new Employee();

$employee->displayDetails();

?>

Sample Output

Employee Name: Amit
Salary: Rs. 35000

Explanation

  • $name and $salary are private properties.
  • Private properties can only be accessed inside the class where they are declared.
  • displayDetails() is public, so it can be called from outside the class.
  • Inside the method, $this accesses the private properties of the current object.

Important: Trying to access $employee->salary directly from outside the class will cause an error because the property is private.

Concepts Covered

  • Private access modifier
  • Private properties
  • Public methods
  • Accessing private properties inside a class

Question 3: Create a Class with Protected Properties

Problem Statement

Create a Person class with a protected property called name. Create a child class named Student that accesses the protected property through a public method.

PHP Solution

<?php

class Person
{
    protected $name = "Rahul";
}

class Student extends Person
{
    public function displayName()
    {
        echo "Student Name: " . $this->name;
    }
}

$student = new Student();

$student->displayName();

?>

Sample Output

Student Name: Rahul

Explanation

  • The Person class contains a protected property called $name.
  • The Student class inherits from Person using extends.
  • Protected properties are accessible inside child classes.
  • The displayName() method accesses $name using $this.
  • The method is public, so it can be called using the child object.

Important: You cannot access $student->name directly from outside the class because the property is protected.

Concepts Covered

  • Protected access modifier
  • Parent and child classes
  • Inheritance using extends
  • Accessing protected properties

Question 4: Use Private Properties with Getter Methods

Problem Statement

Create a Product class with private properties productName and price. Create public getter methods to retrieve both property values.

PHP Solution

<?php

class Product
{
    private $productName = "Laptop";
    private $price = 50000;

    public function getProductName()
    {
        return $this->productName;
    }

    public function getPrice()
    {
        return $this->price;
    }
}

$product = new Product();

echo "Product Name: " . $product->getProductName() . "<br>";
echo "Price: Rs. " . $product->getPrice();

?>

Sample Output

Product Name: Laptop
Price: Rs. 50000

Explanation

  • Both properties are declared as private.
  • getProductName() returns the product name.
  • getPrice() returns the product price.
  • Getter methods provide controlled access to private properties.
  • The returned values can be displayed outside the class.

A getter method is commonly used when you want to read a private property without making it public.

Concepts Covered

  • Private properties
  • Getter methods
  • Returning property values
  • Controlled data access

Question 5: Use Setter Methods to Update Private Properties

Problem Statement

Create a Student class with private properties name and age. Create setter methods to update these properties and a getter method to display their values.

PHP Solution

<?php

class Student
{
    private $name;
    private $age;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function setAge($age)
    {
        $this->age = $age;
    }

    public function getDetails()
    {
        echo "Student Name: " . $this->name . "<br>";
        echo "Age: " . $this->age;
    }
}

$student = new Student();

$student->setName("Priya");
$student->setAge(18);

$student->getDetails();

?>

Sample Output

Student Name: Priya
Age: 18

Explanation

  • The $name and $age properties are private.
  • setName() receives a name and assigns it to the private property.
  • setAge() receives an age and updates the private property.
  • getDetails() displays the stored values.
  • Setter methods allow outside code to update private properties through public methods.

Remember:

  • Getter methods retrieve property values.
  • Setter methods update property values.

Concepts Covered

  • Setter methods
  • Getter methods
  • Private properties
  • Updating object data

Question 6: Apply Validation Using Setter Methods

Problem Statement

Create a BankAccount class with a private property called balance. Create a setter method that allows the balance to be updated only when the new value is zero or greater.

PHP Solution

<?php

class BankAccount
{
    private $balance = 10000;

    public function setBalance($amount)
    {
        if ($amount >= 0) {
            $this->balance = $amount;
            echo "Balance updated successfully.<br>";
        } else {
            echo "Invalid balance. Negative values are not allowed.<br>";
        }
    }

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

$account = new BankAccount();

$account->setBalance(15000);

echo "Current Balance: Rs. " . $account->getBalance() . "<br>";

$account->setBalance(-500);

echo "Current Balance: Rs. " . $account->getBalance();

?>

Sample Output

Balance updated successfully.
Current Balance: Rs. 15000
Invalid balance. Negative values are not allowed.
Current Balance: Rs. 15000

Explanation

  • The $balance property is private.
  • The setBalance() method receives a new balance.
  • The method checks whether the amount is zero or greater.
  • If the value is valid, the balance is updated.
  • If the value is negative, the old balance remains unchanged.
  • getBalance() returns the current balance.

This is an example of encapsulation because the class controls how its important data can be changed.

Concepts Covered

  • Encapsulation
  • Private properties
  • Setter validation
  • Data protection
  • Getter methods

Question 7: Use Protected Properties and Methods in Inheritance

Problem Statement

Create a parent class named Employee with protected properties name and salary. Create a child class named Manager that accesses these properties and displays employee details.

PHP Solution

<?php

class Employee
{
    protected $name = "Amit";
    protected $salary = 45000;

    protected function displaySalary()
    {
        echo "Salary: Rs. " . $this->salary . "<br>";
    }
}

class Manager extends Employee
{
    public function displayDetails()
    {
        echo "Employee Name: " . $this->name . "<br>";

        $this->displaySalary();
    }
}

$manager = new Manager();

$manager->displayDetails();

?>

Sample Output

Employee Name: Amit
Salary: Rs. 45000

Explanation

  • The Employee class contains two protected properties.
  • It also contains a protected method called displaySalary().
  • The Manager class inherits from Employee.
  • The child class can access both protected properties and the protected method.
  • displayDetails() is public, so it can be called from outside the class.

Important: Protected members are accessible inside the parent class and its child classes, but not directly through an object from outside.

Concepts Covered

  • Protected properties
  • Protected methods
  • Inheritance
  • Parent and child classes
  • Accessing inherited members

Question 8: Create a Bank Account Using Encapsulation

Problem Statement

Create a BankAccount class with a private property called balance. Create public methods to deposit money, withdraw money and check the current balance.

Apply these rules:

  • The deposit amount must be greater than zero.
  • The withdrawal amount must be greater than zero.
  • The withdrawal amount cannot exceed the available balance.

PHP Solution

<?php

class BankAccount
{
    private $balance = 10000;

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

            echo "Deposit successful.<br>";
        } else {
            echo "Invalid deposit amount.<br>";
        }
    }

    public function withdraw($amount)
    {
        if ($amount <= 0) {
            echo "Invalid withdrawal amount.<br>";
        } elseif ($amount > $this->balance) {
            echo "Insufficient balance.<br>";
        } else {
            $this->balance -= $amount;

            echo "Withdrawal successful.<br>";
        }
    }

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

$account = new BankAccount();

$account->deposit(5000);

$account->withdraw(3000);

echo "Available Balance: Rs. " . $account->getBalance();

?>

Sample Output

Deposit successful.
Withdrawal successful.
Available Balance: Rs. 12000

Explanation

  • The balance is private, so it cannot be changed directly from outside the class.
  • deposit() checks whether the deposit amount is valid before adding it.
  • withdraw() checks whether the amount is positive and whether enough balance is available.
  • getBalance() returns the current balance.
  • The class controls all balance-related operations through public methods.

This is a practical example of encapsulation because the balance is protected and updated only through controlled operations.

Concepts Covered

  • Encapsulation
  • Private properties
  • Public methods
  • Deposit and withdrawal operations
  • Data validation
  • Controlled access to data

Question 9: Use Different Access Modifiers in an Employee Class

Problem Statement

Create an Employee class with the following members:

  • Public property: name
  • Protected property: department
  • Private property: salary

Create a public method to display all three values. Also create a child class named TeamLeader that accesses the public and protected properties.

PHP Solution

<?php

class Employee
{
    public $name = "Rahul";
    protected $department = "IT";
    private $salary = 50000;

    public function displayDetails()
    {
        echo "Employee Name: " . $this->name . "<br>";
        echo "Department: " . $this->department . "<br>";
        echo "Salary: Rs. " . $this->salary . "<br>";
    }
}

class TeamLeader extends Employee
{
    public function displayTeamDetails()
    {
        echo "Name: " . $this->name . "<br>";
        echo "Department: " . $this->department . "<br>";
    }
}

$employee = new Employee();

$employee->displayDetails();

echo "<br>";

$leader = new TeamLeader();

$leader->displayTeamDetails();

?>

Sample Output

Employee Name: Rahul
Department: IT
Salary: Rs. 50000

Name: Rahul
Department: IT

Explanation

  • The name property is public, so it can be accessed from anywhere.
  • The department property is protected, so it can be accessed inside the parent and child classes.
  • The salary property is private, so it can only be accessed inside the Employee class.
  • displayDetails() can access all three properties because it belongs to the class where they are declared.
  • TeamLeader can access name and department, but it cannot directly access salary.

This example demonstrates how all three access modifiers behave in one program.

Concepts Covered

  • Public, private and protected
  • Access modifier comparison
  • Inheritance
  • Parent and child class access
  • Encapsulation basics

Question 10: Build an Employee Salary Management System Using Encapsulation

Problem Statement

Create an Employee class with private properties for employee name, basic salary, HRA, DA and PF.

Create public setter methods to assign employee details and validate salary values. Create getter methods to retrieve the employee name and calculated net salary.

Use these formulas:

  • Gross Salary = Basic Salary + HRA + DA
  • Net Salary = Gross Salary – PF

PHP Solution

<?php

class Employee
{
    private $name;
    private $basicSalary = 0;
    private $hra = 0;
    private $da = 0;
    private $pf = 0;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function setSalaryDetails($basicSalary, $hra, $da, $pf)
    {
        if (
            $basicSalary >= 0 &&
            $hra >= 0 &&
            $da >= 0 &&
            $pf >= 0
        ) {
            $this->basicSalary = $basicSalary;
            $this->hra = $hra;
            $this->da = $da;
            $this->pf = $pf;
        } else {
            echo "Salary values cannot be negative.<br>";
        }
    }

    public function getName()
    {
        return $this->name;
    }

    public function calculateGrossSalary()
    {
        return $this->basicSalary + $this->hra + $this->da;
    }

    public function calculateNetSalary()
    {
        return $this->calculateGrossSalary() - $this->pf;
    }

    public function displaySalaryDetails()
    {
        echo "Employee Name: " . $this->getName() . "<br>";
        echo "Basic Salary: Rs. " . $this->basicSalary . "<br>";
        echo "HRA: Rs. " . $this->hra . "<br>";
        echo "DA: Rs. " . $this->da . "<br>";
        echo "PF: Rs. " . $this->pf . "<br>";
        echo "Gross Salary: Rs. " . $this->calculateGrossSalary() . "<br>";
        echo "Net Salary: Rs. " . $this->calculateNetSalary();
    }
}

$employee = new Employee();

$employee->setName("Amit");

$employee->setSalaryDetails(30000, 6000, 4000, 3000);

$employee->displaySalaryDetails();

?>

Sample Output

Employee Name: Amit
Basic Salary: Rs. 30000
HRA: Rs. 6000
DA: Rs. 4000
PF: Rs. 3000
Gross Salary: Rs. 40000
Net Salary: Rs. 37000

Explanation

  • All employee properties are private, so they cannot be accessed directly from outside the class.
  • setName() assigns the employee name.
  • setSalaryDetails() checks that all salary values are zero or greater before updating the properties.
  • getName() returns the employee name.
  • calculateGrossSalary() calculates the total salary before PF deduction.
  • calculateNetSalary() calculates the salary after PF deduction.
  • displaySalaryDetails() displays the employee’s information and salary calculations.

This example combines private properties, public methods, validation and controlled data access to demonstrate encapsulation in a practical application.

Concepts Covered

  • Complete encapsulation
  • Private properties
  • Public setter and getter methods
  • Data validation
  • Salary calculations
  • Controlled property access
  • Practical PHP OOP programming

Key Takeaways

After completing this chapter, you should understand:

  • Access modifiers control where class properties and methods can be accessed.
  • public members can be accessed from anywhere.
  • private members can only be accessed inside the class where they are declared.
  • protected members can be accessed inside their class and child classes.
  • Encapsulation means protecting class data and controlling how it is accessed.
  • Getter methods are used to retrieve private property values.
  • Setter methods are used to update private property values.
  • Setter methods can validate data before updating properties.
  • Private properties help prevent uncontrolled changes to important information.
  • Public methods provide controlled access to private data.

Frequently Asked Questions (FAQs)

1. What are access modifiers in PHP?

Access modifiers are keywords that control where class properties and methods can be accessed. PHP provides three main access modifiers: public, private and protected.

2. What is the difference between public and private in PHP?

Public properties and methods can be accessed from inside and outside the class. Private properties and methods can only be accessed inside the class where they are declared.

3. What is the use of protected in PHP?

The protected keyword allows properties and methods to be accessed inside their own class and its child classes. They cannot be accessed directly from outside.

4. What is encapsulation in PHP?

Encapsulation is an OOP concept that protects class data and provides controlled access through methods. It is commonly implemented using private properties and public getter and setter methods.

5. What is a getter method in PHP?

A getter method is a public method that returns the value of a private or protected property.

6. What is a setter method in PHP?

A setter method is a public method used to update a private or protected property. It can also validate the new value before changing the property.

7. Can we access private properties outside a PHP class?

No. Private properties cannot be accessed directly outside the class where they are declared. You can provide public methods to read or update them.

8. Can a child class access private properties of its parent class?

No. A child class cannot directly access private properties declared in its parent class. It can access inherited public and protected members.

9. Why is encapsulation important in PHP?

Encapsulation helps protect important data, prevent uncontrolled changes and keep the class logic organized. For example, a bank account balance can be updated only through deposit and withdrawal methods.

10. Can methods also have access modifiers in PHP?

Yes. Methods can be declared as public, private or protected, just like properties.

11. Which access modifier should beginners use for class properties?

When a property needs controlled access, private is often a good starting choice. Public methods can then provide the required access.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top