Skip to content

Instantly share code, notes, and snippets.

@thgs
Last active February 22, 2016 07:59
Show Gist options
  • Save thgs/17e71028170a34067edb to your computer and use it in GitHub Desktop.
Save thgs/17e71028170a34067edb to your computer and use it in GitHub Desktop.
with for PHP
<?php
/* with operator for PHP */
function with(&$obj, $properties)
{
foreach ($properties as $property => $value)
{
$obj->$property = $value;
}
}
$a = new stdClass;
with($a, array('someProp' => true, 'someOther' => 123));
var_dump($a);
<?php
/* another with operator for PHP */
function with( &$obj, array $properties, $mapFunc = null)
{
if (!is_object($obj))
{
throw new \Exception('Not an object!');
}
foreach ($properties as $property => $value)
{
$obj->$property = (is_callable($mapFunc)) ? $mapFunc($value) : $value;
}
return $obj;
}
$a = new stdClass;
with($a, array('someProp' => false, 'someOther' => -123), 'abs');
#var_dump($a);
class anotherClass {}
$o = new anotherClass;
with($o, array('some' => 123, 2), 'abs');
#var_dump($o);
$objects = [$a, $o];
$properties = [['new_prop_for_a' => 1], ['new_prop_for_o' => 'ooo']];
list($obj1, $obj2) = array_map('with', $objects, $properties);
var_dump($obj1, $obj2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment