Last active
August 31, 2016 13:54
-
-
Save shadowhand/01194ef9c4a0481ba78a7032239dbb17 to your computer and use it in GitHub Desktop.
Private object hydration via closure
This file contains hidden or 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 | |
| use function Magic\hydrate; | |
| class Foo | |
| { | |
| private $cute; | |
| private $clever; | |
| public function __construct(array $values) | |
| { | |
| hydrate($values)->call($this); | |
| } | |
| } |
This file contains hidden or 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 | |
| namespace Magic; | |
| /** | |
| * Create a hydrator from an array. | |
| * | |
| * @param array $values | |
| * | |
| * @return Closure | |
| */ | |
| function hydrate(array $values) | |
| { | |
| return function () use ($values) { | |
| foreach ($values as $key => $value) { | |
| $this->$key = $value; | |
| } | |
| }; | |
| } |
This file contains hidden or 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 | |
| $foo = new Foo([ | |
| 'cute' => 'sure', | |
| 'clever' => true, | |
| ]); | |
| var_dump($foo); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This only works in PHP 7+.