Created
October 4, 2017 11:31
-
-
Save feyyazesat/d0c0839df11b001d7144616d2aa68abf to your computer and use it in GitHub Desktop.
Violation of Encapsulation Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Following Explanation From Wikipedia | |
https://en.wikipedia.org/wiki/Encapsulation_(computer_programming) | |
Encapsulation is used to hide the values or state of a structured data object inside a class | |
*/ | |
class AClass { | |
private $propertyDoesntViolateEncapsulation = 0; | |
private static $propertyViolatesEncapsulation = 0; | |
public function methodDoesntViolateEncapsulation() | |
{ | |
return ++$propertyDoesntViolateEncapsulation; | |
} | |
public static function methodViolatesEncapsulation() | |
{ | |
return ++$propertyViolatesEncapsulation; | |
} | |
} | |
// Example below doesn't interfere each other in anyway | |
// . They are not coupled | |
// . They do not share any state so they cannot corrupt each other's state. | |
// . They are not aware each other | |
$anObject = new AClass(); | |
$anObject->methodDoesntViolateEncapsulation(); | |
$anotherObject = new AClass(); | |
$anotherObject->methodDoesntViolateEncapsulation(); | |
// But now things come to a silly point. | |
// They basically set each other's state currently we coupled these 2 objects to each other by sharing a state | |
// This violates encapsulation. anObject accessed to anotherObject's state and otherway around. | |
$anObject::methodViolatesEncapsulation(); | |
$anotherObject::methodViolatesEncapsulation(); | |
$anObject::methodViolatesEncapsulation(); | |
$anotherObject::methodViolatesEncapsulation(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment