What is the best method to merge two PHP objects?
What is the best method to merge two PHP objects?
Here are a few methods to merge two PHP objects:
The + operator can be used to merge two objects. It will add the properties of the right object to the left object, overwriting any properties with the same name:
$obj1 = (object) ['name' => 'John', 'age' => 30];
$obj2 = (object) ['city' => 'New York', 'age' => 35];
$merged = $obj1 + $obj2;
print_r($merged);
Output:
stdClass Object
(
[name] => John
[age] => 35
[city] => New York
)
You can convert the objects to arrays, merge the arrays, and then convert back to an object:
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.