Tags

, , , ,

Just published! My new book on Laravel 5.7.*: Middleware, Authentication, Authorization Explained: How to Authenticate a company, projects and tasks management application.

Just published! My new book on Beginning Ethical Hacking with Kali Linux: Computational Techniques for Resolving Security Issues.

How to build a PHP 7 Framework

How to build a PHP 7 Framework

https://leanpub.com/How-to-Build-A-PHP-MVC-Framework

To get Books of 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.


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

php7 in 7 days

php7 in 7 days

Advertisements