Please wait

Encapsulation (OOP Principle)

At the most basic level, encapsulation in PHP is about keeping some pieces of data ("properties") and actions ("methods") tucked away inside a class, so they can't be accessed or messed up directly from outside. We can think of a class as a kind of capsule or box that holds and protects its content.

Why is this a good thing? Well, imagine you have a piggy bank. You wouldn't want anyone to be able to take money out of it or put anything inside it directly. So, you have a small slot to put coins in, and you have a way (like a plug or a hammer) to get money out. Encapsulation works in a similar way with classes in PHP.

Using access modifiers

As a recap, we learned about access modifiers, which give us the power to change the accessibility of a property or method. This is how encapsulation is applied in PHP.

For example, consider a simple PiggyBank class. We can use private for our properties and define public methods to interact with the property like so:

class PiggyBank {
  private $amount = 0;  // This is a property
 
  public function addCoin($coin) {
    // Code here...
  }
 
  public function shake() {
    // Code here...
  }
}

In this PiggyBank class, $amount is a private property. This means it can't be accessed directly from outside the class. We can only interact with the piggy bank using the addCoin($coin) and shake() methods. These methods control how we can interact with the piggy bank, and they ensure that we can't do anything that wouldn't make sense, like adding an invalid coin. This is the core idea of encapsulation!

The protected modifiers

Of course, things get trickier when you add inheritance to the picture. When we deal with inheritance, it is important to be able to control the visibility of properties (and methods). We have three levels of visibility: public, private, and protected.

  • Public properties are accessible everywhere, both inside and outside of the class and by child classes.
  • Private properties are only accessible within the class where they are declared. This means if you have a private property in a parent class, you cannot directly access it from its child classes.

This restriction can lead to problems. Consider an example where a child class needs to use or modify a property from its parent class. If the property is private, it's not accessible from the child class, even though it makes sense for the child class to be able to access properties from its parent.

That's where the protected visibility modifier comes in. A protected property is accessible within the class where it's declared and by any child classes but not from outside these classes.

Using the protected modifier

Let's now introduce a new type of piggy bank, a SavingsPiggyBank. This piggy bank is special because it can accumulate interest over time. In order to add this functionality, we need to have access to the $amount property from our new child class. If $amount was private, we wouldn't be able to access it from SavingsPiggyBank, so we'll make it protected.

Here is how we can do it:

class PiggyBank {
  // Changed from "private" to "protected"
  protected $amount = 0;
 
  public function addCoin($coin) {
    $this->amount += $coin;
  }
 
  public function shake() {
    // Code here...
  }
}

Next, we can define a SavingsPiggyBank class to extend the PiggyBank class with a method called addInterest():

class SavingsPiggyBank extends PiggyBank {
  public function addInterest($interestRate) {
    // We can access $amount because it's protected in the parent class
    $this->amount += $this->amount * $interestRate;
  }
}

In this example, SavingsPiggyBank is a child class of PiggyBank, and it needs to use the $amount property to add the interest to the existing amount. Since $amount is declared as protected in PiggyBank, SavingsPiggyBank can access it directly.

We can use our SavingsPiggyBank class like so:

// Now, let's see how we can use our SavingsPiggyBank
$savingsPiggyBank = new SavingsPiggyBank();
$savingsPiggyBank->addCoin(10);
$savingsPiggyBank->addInterest(0.1);  // We add 10% interest to our piggy bank.

At the same time, you can't access the $amount property outside of the classes. Attempting to do would result in an error:

// Throws an error
echo $savingsPiggyBank->amount;

Key Takeaways

  • Encapsulation is one of the four fundamental principles of Object-Oriented Programming (OOP). It's the practice of hiding internal state and behavior inside a class and only exposing necessary parts to the outside world. This is achieved by using private and protected properties and methods.
  • Encapsulation improves code maintenance and understanding by preventing external code from being overly dependent on the internal workings of a class.
  • The public, private, and protected keywords are used to set the visibility of properties and methods in PHP classes.
  • Protected properties and methods fall between public and private: they can be accessed within the class they're declared in and from child classes, but not from outside these classes.
  • When it comes to inheritance, the protected modifier plays an important role. If a property or method in a parent class is declared as protected, it can be directly accessed by child classes.
  • Using protected instead of private gives you a balance between security and flexibility. Your properties and methods are still hidden from the outside world but can be used and overridden by child classes if needed.

Comments

Please read this before commenting