Forked from feyyazesat/violation-of-encapsulation-example.php
Last active
October 4, 2017 12:26
-
-
Save xprt64/14638467d02f59bbb4127f4415c5017c 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; | |
} | |
public static function butThisMethodDoesNotViolatesEncapsulation(int $initialCounter):self | |
{ | |
$other = new self(); | |
$other->propertyDoesntViolateEncapsulation = $initialCounter; | |
return $other; | |
} | |
} | |
// 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(); | |
// Here is the example that is relevant to our discussion | |
$someOtherObject = AClass::butThisMethodDoesNotViolatesEncapsulation(10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment