Created
March 22, 2016 08:54
-
-
Save trivago-makbarof/bb693a5db23c5b144d93 to your computer and use it in GitHub Desktop.
Allow modification of object only upon creation
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 | |
class Person | |
{ | |
private $firstName; | |
private $lastName; | |
private function __construct() | |
{ | |
} | |
public function getFirstName() | |
{ | |
return $this->firstName; | |
} | |
public function getLastName() | |
{ | |
return $this->lastName; | |
} | |
public static function create() | |
{ | |
$instance = new static(); | |
return new PersonEditor($instance, function($field, $value) use ($instance) { | |
$instance->$field = $value; | |
}); | |
} | |
} | |
class PersonEditor | |
{ | |
private $editor; | |
private $instance; | |
public function __construct(Person $instance, Closure $editor) | |
{ | |
$this->instance = $instance; | |
$this->editor = $editor; | |
} | |
public function setFirstName($firstName) | |
{ | |
call_user_func_array($this->editor, ['firstName', $firstName]); | |
} | |
public function setLastName($lastName) | |
{ | |
call_user_func_array($this->editor, ['lastName', $lastName]); | |
} | |
public function getInstance() | |
{ | |
return $this->instance; | |
} | |
} | |
$personEditor = Person::create(); | |
$personEditor->setFirstName('Moein'); | |
$personEditor->setLastName('Akbarof'); | |
$person = $personEditor->getInstance(); | |
var_dump($person->getFirstName(), $person->getLastName()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment