Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xprt64/14638467d02f59bbb4127f4415c5017c to your computer and use it in GitHub Desktop.
Save xprt64/14638467d02f59bbb4127f4415c5017c to your computer and use it in GitHub Desktop.
Violation of Encapsulation Example
<?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