Header Ads

Object-Oriented PHP: Encapsulation

In our previous lesson we've learned about Getters and Setters. We've learned why getters and setters are so important. In this lesson we will be talking about encapsulation.

When I was first learning Object-Oriented Programming, the word "encapsulation" sounds to me like a very complicated pattern or concepts. But like most things, once I dig in a little bit more, I realize that it's not the most difficult thing in the world. In fact, it's just something to do with using the right keyword in your class methods and properties. You have three choices, the public, private, and the protected keyword.

When you say public methods or public properties, those methods and properties will be accessible inside and outside the class. However, when you say private, it will be only accessible inside the class, while the protected it is only accessible inside the class and in the child class. Child class meaning the class that extends another class or the parent class. Don't worry, we will be talking about inheritance in out next lesson.

Why use encapsulation? There are lot of explanation out there on why we use encapsulation. But for me the simple explanation is in order to hide those properties and methods that you think will not make sense if you're going to expose them in public.

So, we can now solve the problem in our previous lesson that we can still reference those properties directly and enforce to use those getter and setter methods.

class Person {
    private $name;
    private $age;

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

    public function setAge($age)
        if ($age < 18) {
            throw new Exception('Age must be at least 18 years old.');

        $this->age = $age;

    public function getAge()
        return 'I am ' . $this->age . ' years old';

$user = new Person('John Doe');
$user->age = 10;


As you can see when we run this code, we're getting a fatal error which is really exactly what we want in this case.
D:\Tutorials\Laragle\PHP\OOP>php Person.php

Fatal error: Cannot access private property Person::$age in D:\Tutorials\Laragle
\PHP\OOP\Person.php on line 28

That's all there is to it and that's encapsulation in a nutshell. In our next lesson we will be talking about inheritance. Stay tuned.

Previous: Getters and SettersNext: Inheritance

No comments