Last active
October 4, 2015 16:43
-
-
Save impeto/b36e18d2051256affd1c to your computer and use it in GitHub Desktop.
How getters solve encapsulation
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 | |
calss Date { | |
public $date; | |
public function __construct( $date){ | |
$this->date = $date; | |
} | |
//other methods | |
} | |
class Man { | |
public $dob ; | |
public function __construct( Date $dob){ | |
$this->dob = $dob; | |
} | |
} | |
//I can easily do this: | |
$man = new Man( new Date( '01/01/1990')); | |
$man->dob->date = '01/01/1716'; //My $man is now a vampire | |
class YoungMan { | |
private $dob; | |
public function __construct( Date $dob){ | |
$this->dob = $dob; | |
} | |
/** | |
* External code can only get a copy of the $dob field. | |
* Changeing it does not affect the internal state of the YoungMan object | |
*/ | |
public function getDob(){ | |
return new Date( $this->dob->date); | |
} | |
public function setDob( Date $newDob){ | |
//check the date to see if it's within 'human' range | |
//if it is, set it | |
//if not throw a new Exception | |
} | |
} | |
//now when you do | |
$youngMan = new YoungMan( new Date( '01/01/2000')); | |
//you cant's do $youngMan->dob->date = '01/01/2050' | |
//you have to do | |
$youngManDOB = $youngMan->getDob(); | |
//you can do | |
$youngManDOB->date = '01/01/2050'; | |
//but that doesn't affect the DOB of $youngMan | |
//in order to affect that, you have to do | |
$youngMan->setDob( new Date('01/01/2050')); | |
//if the new date is not within the accepted range, | |
//an Exception will be thrown, but the internal state of $youngMan is preserved |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment