PHP Objects 3: All you should know About PHP OOP

PHP Objects 3 All you should know About PHP OOP
PHP Objects 3 All you should know About PHP OOP

Let’s Breakdown the PHP Objects Encapsulation and Access Modifiers which explores the concepts of encapsulation and access modifiers in PHP’s object-oriented programming.


PHP Objects 2: Overview

Before then To begin with this section you may want to see our initial PHP Objects 2: All you should know about PHP OOP that covers PHP object-oriented programming, including calling object methods with parameters, inheritance, polymorphism, and practical examples of polymorphism in payment processing.


Let’s Continue with this section

Encapsulation and Access Modifiers in PHP: Safeguarding Your Code

Encapsulation and access modifiers are foundational principles in object-oriented programming (OOP). They enable you to control the visibility and accessibility of class properties and methods, enhancing code security and maintainability. In this section, we’ll delve into encapsulation, access modifiers, and how they safeguard your PHP code.

Encapsulation: Data Protection and Organization

Encapsulation is the practice of bundling data (properties) and the methods (functions) that operate on that data within a single unit, known as a class. It ensures that data is accessed and modified through well-defined methods, reducing the risk of unintended changes.

Example (Encapsulation):

class Employee {
    private $name;
    private $salary;

    public function __construct($name, $salary) {
        $this->name = $name;
        $this->salary = $salary;
    }

    public function getSalary() {
        return $this->salary;
    }
}

In this example, the Employee class encapsulates the name and salary properties. These properties are marked as private, meaning they can only be accessed or modified from within the class. The getSalary method is a controlled way to access the salary property.

Access Modifiers: Restricting Access

Access modifiers are keywords that specify the visibility and accessibility of class members (properties and methods). PHP provides three main access modifiers:

  • Public: Members are accessible from anywhere.
  • Protected: Members are accessible from the class itself and its subclasses (child classes).
  • Private: Members are only accessible from the class itself.

Example (Access Modifiers):

class BankAccount {
    private $balance;

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

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

In this example, the balance property is marked as private, restricting direct access from outside the class. The deposit method allows controlled modification of the balance, while the getBalance method provides read-only access.

Object-Oriented Security

Encapsulation and access modifiers play a crucial role in code security. By encapsulating data and using access modifiers, you safeguard your code against unintended or unauthorized access and modifications. This promotes data integrity and reduces the risk of bugs.

Encapsulation in Real-World Scenarios

In the context of real-world scenarios like building a bank application, encapsulation is vital. Protecting sensitive data and controlling access ensures that the financial system operates securely and correctly.

Object-Oriented Structure

Encapsulation and access modifiers are foundational concepts in object-oriented programming. They contribute to code organization, security, and maintainability. By adhering to these principles, you can build robust and reliable PHP applications.


In summary explains the concepts of encapsulation and access modifiers in PHP, highlighting their roles in safeguarding code and promoting organized and secure object-oriented programming.

More Examples on Encapsulation and Access Modifiers in PHP

Certainly, let’s provide more examples to deepen your understanding of encapsulation and access modifiers in PHP.

Example 1: Private Property Access

Encapsulation Example (Private Property Access):

class BankAccount {
    private $balance;

    public function __construct($initialBalance) {
        $this->balance = $initialBalance;
    }

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

    public function withdraw($amount) {
        if ($amount <= $this->balance) {
            $this->balance -= $amount;
            return true;
        } else {
            return false;
        }
    }

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

// Creating a bank account
$account = new BankAccount(1000);

// Attempting to access the balance directly (will result in an error)
// $balance = $account->balance;

// Using the getBalance method to access the balance
$balance = $account->getBalance(); // $balance will be 1000

In this example, the balance property is marked as private. Attempting to access it directly from outside the class results in an error. To access the balance, you must use the public getBalance method, which enforces encapsulation.

Example 2: Protected Property and Inheritance

Access Modifiers Example (Protected Property and Inheritance):

class Person {
    protected $name;

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

class Employee extends Person {
    private $salary;

    public function __construct($name, $salary) {
        parent::__construct($name);
        $this->salary = $salary;
    }

    public function getSalary() {
        return $this->salary;
    }
}

$employee = new Employee('John Doe', 50000);

// Attempting to access $name directly (will result in an error)
// $name = $employee->name;

// Using the protected property via the parent class's constructor
$name = $employee->getSalary(); // $name will be 'John Doe'

In this example, the name property is marked as protected in the Person class. The Employee class inherits the name property and provides a way to access it via the parent class’s constructor, demonstrating how access modifiers impact inheritance.

Example 3: Public Methods and Encapsulation

Encapsulation Example (Public Methods and Encapsulation):

class ShoppingCart {
    private $items = [];

    public function addItem($product, $quantity) {
        $this->items[$product] = $quantity;
    }

    public function removeItem($product) {
        if (isset($this->items[$product])) {
            unset($this->items[$product]);
        }
    }

    public function getItems() {
        return $this->items;
    }
}

$cart = new ShoppingCart();

$cart->addItem('Product A', 2);
$cart->addItem('Product B', 1);

$items = $cart->getItems();
// $items will contain the array of items added to the shopping cart

In this example, the items property is marked as private, ensuring that it is accessed and modified only through the public methods provided by the ShoppingCart class.

Object-Oriented Best Practices

Encapsulation and access modifiers are vital for maintaining clean, secure, and well-structured code. They provide a clear interface for interacting with class properties and ensure data integrity in complex applications.

These additional examples showcase the practical implementation of encapsulation and access modifiers in various scenarios, reinforcing their importance in object-oriented programming.

Certainly, let’s create plagiarism-free and well-optimized content for subheading 6.1, “Public, Private, and Protected,” which explores the different access modifiers in PHP’s object-oriented programming.


Public, Private, and Protected Access Modifiers in PHP: Controlling Visibility

Access modifiers are an essential aspect of object-oriented programming in PHP. They define the visibility and accessibility of class members, such as properties and methods. In this section, we’ll explore the three main access modifiers: public, private, and protected, and how they control visibility within classes.

Public: Full Accessibility

Public is the least restrictive access modifier. Members declared as public are accessible from anywhere, both within and outside the class.

Example (Public Access Modifier):

class Example {
    public $publicProperty;

    public function publicMethod() {
        return 'This is a public method.';
    }
}

$example = new Example();
$example->publicProperty = 'This is a public property.';
$result = $example->publicMethod();

In this example, the publicProperty and publicMethod are declared as public. They can be accessed and called from anywhere in your PHP code.

Private: Restricted to the Class

Private is the most restrictive access modifier. Members declared as private are only accessible within the class in which they are defined. They cannot be accessed or modified from outside the class.

Example (Private Access Modifier):

class Example {
    private $privateProperty;

    private function privateMethod() {
        return 'This is a private method.';
    }

    public function accessPrivate() {
        return $this->privateMethod();
    }
}

$example = new Example();
// Attempting to access a private property or method will result in an error
// $example->privateProperty = 'This will cause an error.';
// $result = $example->privateMethod();
$result = $example->accessPrivate();

In this example, both the privateProperty and privateMethod are marked as private. Attempting to access them directly from outside the class will result in an error. However, you can provide controlled access to private members using public methods within the class, as demonstrated by the accessPrivate method.

Protected: Limited to Class and Subclasses

Protected allows members to be accessed within the class and its subclasses (child classes). It restricts access from outside the class and is often used in the context of inheritance.

Example (Protected Access Modifier):

class ParentClass {
    protected $protectedProperty;

    protected function protectedMethod() {
        return 'This is a protected method.';
    }
}

class ChildClass extends ParentClass {
    public function accessProtected() {
        return $this->protectedMethod();
    }
}

$parent = new ParentClass();
$child = new ChildClass();

// Attempting to access a protected property or method from outside the class or subclass will result in an error
// $parent->protectedProperty = 'This will cause an error.';
// $result = $parent->protectedMethod();
$result = $child->accessProtected();

To demonstraIn this example, the protectedProperty and protectedMethod belong to the ParentClass. They are accessible in the ChildClass, but any direct access from outside both classes will result in an error.

Choosing the Right Access Modifier

The choice of access modifier depends on the level of visibility and accessibility you want for class members. Public members are accessible from anywhere, private members are confined to the class, and protected members can be accessed within the class and its subclasses.

By selecting the appropriate access modifier, you can control the encapsulation and organization of your code, enhancing security and maintainability.

In summary explains the different access modifiers in PHP—public, private, and protected—highlighting how they control visibility within classes.

Extra Examples on Public, Private, and Protected Access Modifiers in PHP

Certainly, let’s provide more examples focusing on payment processing to illustrate the usage of public, private, and protected access modifiers in PHP.

Example 1: Public Access Modifier

Public Access Modifier in Payment Processing:

class PaymentProcessor {
    public $publicPaymentInfo;

    public function __construct($paymentInfo) {
        $this->publicPaymentInfo = $paymentInfo;
    }

    public function processPayment() {
        return 'Processing payment: ' . $this->publicPaymentInfo;
    }
}

$paymentProcessor = new PaymentProcessor('Credit Card');
$result = $paymentProcessor->processPayment();

echo $result;

In this example, the publicPaymentInfo property is declared as public. It can be accessed and modified from outside the class. The processPayment method utilizes this public property to process payments.

Example 2: Private Access Modifier

Private Access Modifier in Payment Processing:

class Payment {
    private $creditCardNumber;

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

    public function processPayment() {
        return 'Processing payment with card ending in ' . substr($this->creditCardNumber, -4);
    }
}

$payment = new Payment('1234-5678-9012-3456');

// Attempting to access the private property will result in an error
// $creditCard = $payment->creditCardNumber;
$result = $payment->processPayment();

echo $result;

To illustrate in this example, the creditCardNumber property is declared as private. It can only be accessed and modified within the class. The processPayment method, however, can use this private property to process payments while keeping the actual card number protected.

Example 3: Protected Access Modifier

Protected Access Modifier in Payment Processing:

class BankAccount {
    protected $balance;

    public function __construct($initialBalance) {
        $this->balance = $initialBalance;
    }

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

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

class SavingsAccount extends BankAccount {
    public function addInterest($interest) {
        $this->balance += $this->balance * ($interest / 100);
    }
}

$savingsAccount = new SavingsAccount(1000);

// Attempting to access the protected property directly from outside the class or subclass will result in an error
// $balance = $savingsAccount->balance;
$savingsAccount->deposit(500);
$balance = $savingsAccount->getBalance();

echo 'Current balance: $' . $balance;

In this example, the balance property is declared as protected in the BankAccount class. It is accessible within the class and its subclass, SavingsAccount. Attempting to access the protected property directly from outside the class or subclass will result in an error. The subclass, however, can use it to add interest to the balance.

These examples demonstrate how access modifiers (public, private, and protected) can be applied in payment processing classes to control visibility and access to properties, making payment processing more secure and organized.

NEXT > PHP Objects 4: All you should know About PHP OOP

LEAVE A REPLY

Please enter your comment!
Please enter your name here