Skip to content

Instantly share code, notes, and snippets.

@mayoz
Forked from CWSpear/object_merge.php
Created January 30, 2013 14:23
Show Gist options
  • Save mayoz/4673579 to your computer and use it in GitHub Desktop.
Save mayoz/4673579 to your computer and use it in GitHub Desktop.
<?php
$one->one = 1;
$two->two->one = 21;
$two->two->two = 22;
$three->two->one = 31;
$return_obj = object_merge($one, $two, $three);
// returns:
// Array
// (
// [one] => 1
// [two] => Array
// (
// [one] => 31
// )
//
// )
$a_one['one'] = 1;
$a_two['two']['one'] = 21;
$a_two['two']['two'] = 22;
$a_three['two']['one'] = 31;
$return_arr = array_merge($a_one, $a_two, $a_three);
// returns:
// stdClass Object
// (
// [one] => 1
// [two] => stdClass Object
// (
// [one] => 31
// )
//
// )
// just like array_merge, you can pass in as many objects (instead of arrays) as you want
function object_merge()
{
// so we can pass in any number of parameters
$params = func_get_args();
// convert each parameter to an array
foreach ($params as $key => $value)
{
$params[$key] = (array) $value;
}
// do a classic array_merge and cast to an object
return (object) call_user_func_array(array_merge, $params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment