Skip to content

Instantly share code, notes, and snippets.

@shadowhand
Last active August 31, 2016 13:54
Show Gist options
  • Save shadowhand/01194ef9c4a0481ba78a7032239dbb17 to your computer and use it in GitHub Desktop.
Save shadowhand/01194ef9c4a0481ba78a7032239dbb17 to your computer and use it in GitHub Desktop.
Private object hydration via closure
<?php
use function Magic\hydrate;
class Foo
{
private $cute;
private $clever;
public function __construct(array $values)
{
hydrate($values)->call($this);
}
}
<?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;
}
};
}
<?php
$foo = new Foo([
'cute' => 'sure',
'clever' => true,
]);
var_dump($foo);
@shadowhand
Copy link
Author

This only works in PHP 7+.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment