Tags

, , , ,

To get Books of Sanjib Sinha…

To know more about Sanjib Sinha….

object-oriented-design-patterns-in-php7 for web

object-oriented-design-patterns-in-php7 for web

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.

I’m a Full-Time writer. If you find these articles helpful please consider buying any of my books.
You can buy from either Leanpub or
Amazon or from my publisher
Apress.


//Day2/instrument.php
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');
$guiter->setWeight(30);
var_dump($guiter->getWeight());

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..

Advertisements