Getter and Setter in PHP 7

Get, Set and Go…

In any class the properties play very roles. Till now we use ‘public’ before every property. In the real world the situation may not be same.
Imagine an ‘Instrument’ class. In the construct part you can pass the name of the instrument. Besides, you can have a property – ‘weight’. Let us write the code first and see the output.

name = $name;        

$guiter = new Instrument('Elictric Guiter');
$guiter->weight = 10;

If we use ‘var_dump($guiter)’ we know what will be the output.

object(Instrument)#1 (2) { ["name"]=> string(15) "Elictric Guiter" ["weight"]=> int(10) }

Now consider a situation where the weight of the guiter should be less than 2 KG.
The logic is simple. We set the weight first and then get the output. In the ‘set’ function we may use ‘if-else’ logic. There is no problem in doing that. Let’s try.

name = $name;        
    public function getWeight() {
        return $this->weight;
    public function setWeight($weight) {
        if ($weight > 2){
            throw new Exception('The weight is not permissible.');            
        $this->weight = $weight;

$guiter = new Instrument('Elictric Guiter');

It promptly throws the fatal error.

PHP Fatal error: Uncaught Exception: The weight is not permissible. in /home/hagudu/Code/php7book1/Day2/instrument.php:20
Stack trace:
#0 /home/hagudu/Code/php7book1/Day2/instrument.php(28): Instrument->setWeight(30)
#1 {main}
thrown in /home/hagudu/Code/php7book1/Day2/instrument.php on line 20

Using this logic we’re still in danger. Since the property ‘weight’ is ‘public’ it still can be accessed directly. Whatever precaution we take may not come to our use, unless we change the ‘access modifier’ of the property which is ‘public’.
The question of hiding our business logic from public gaze comes to our mind. The idea of encapsulation also comes handy in such cases. In the next chapter we’ll deal with that.
For further reading..


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s