Skip to content

Instantly share code, notes, and snippets.

@jasny
Last active October 2, 2019 10:54
Show Gist options
  • Save jasny/5365fe882c5c59bab0f9b01a28385e1d to your computer and use it in GitHub Desktop.
Save jasny/5365fe882c5c59bab0f9b01a28385e1d to your computer and use it in GitHub Desktop.
Set the properties (including protected and private) of an object
<?php
/**
* Set the properties (including protected and private) of an object.
* This should only be called by the object itself.
*/
function object_init(object $object, array $values): void
{
$init = function ($values) {
foreach ($values as $prop => $value) {
$this->{$prop} = $value;
}
};
$init->call($object, $values);
}
<?php
class Foo
{
private $one;
protected $two;
public $three;
public function __construct($one, $two, $three)
{
object_init($this, get_defined_vars());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment