Object-Oriented PHP: Getters and Setters


In our previous lesson we've learned about Classes. We've learned how to create and instantiate a class, how to get and set the value of a class property. In this lesson we will be talking about getters and setters.

Let's say we have a Person class, and when we create a new Person or instantiate a new Person object, we will require a name to be given. We've learned that we can use the constructor for that, right?
<?php

class Person {
    public $name;

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

$user = new Person('John Doe');

var_dump($user->name);
We know this works just fine, right? So, in what situations where we must use getters and setters?

The reason why we use getter and setter methods is to give our selves a little bit of security and protection. So, for example, let's say in our application, we are not going to allow a user with an age below 18 years old.
<?php

class Person {
    public $name;
    public $age;

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

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

var_dump($user->age);
As you can see, when we directly set our age property to 10 ($user->age = 10;), we don't have the ability to enforce our rule that a user must be at least 18 years old. The worst case scenario for this, is when this kind of stuff is scattered throughout our entire application and in the future we are going to enforce a new rules. Because we are referencing these properties directly, those new rules will be very difficult to enforce. So, let's fix that.

The convention in naming your getters and setters is to prefix your method name with get and set respectively:
<?php

class Person {
    public $name;
    public $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->setAge(18);

var_dump($user->getAge());
Now, rather than accessing age property directly, we are now going to use the setAge and getAge methods. We have now the place where we can enforce our rules and behavior.

But, we still have the problem of referencing and accessing the property directly, because right now we can still use the $user->age = 10; even if we already have the getter and setter methods. Well, that's when encapsulation will come into play, which we will discuss in our next lesson. Stay tuned!

Previous: ClassesNext: Encapsulation