Last active
February 22, 2016 07:59
-
-
Save thgs/17e71028170a34067edb to your computer and use it in GitHub Desktop.
with for PHP
This file contains 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 | |
/* 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); |
This file contains 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 | |
/* 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