Skip to content

Instantly share code, notes, and snippets.

@jasny
Last active Oct 2, 2019
Embed
What would you like to do?
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