DEV Community

Ghulam Mujtaba
Ghulam Mujtaba

Posted on

1

Encapsulation in OOP

Encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that binds together the data and the methods that manipulate that data, keeping both safe from outside interference and misuse.

In PHP, encapsulation is achieved by using classes and objects to wrap data (properties) and methods that operate on that data. This helps to:

  • Hide internal implementation details

  • Protect data from external interference

  • Improve code organization and structure

  • Enhance data security and integrity

How to achieve encapsulation in OOP php?

To achieve encapsulation in PHP, we can use:

  • Access modifiers (public, protected, private) to control access to properties and methods

  • Constructors to initialize objects

  • Getters and setters to access and modify properties

<?php 

class BankAccount {
    private $balance;

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

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

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

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

$account = new BankAccount(1000);
echo $account->getBalance(); // Outputs: 1000
$account->deposit(500);
echo $account->getBalance(); // Outputs: 1500
$account->withdraw(200);
echo $account->getBalance(); // Outputs: 1300
Enter fullscreen mode Exit fullscreen mode

In this example, the BankAccount class encapsulates the $balance property and provides methods to interact with it, while hiding the internal implementation details.

I hope that you have clearly understood it.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay