Câu hỏi phỏng vấn PHP
Câu hỏi

What is the best method ...

Câu trả lời

Here are a few methods to merge two PHP objects:

Using the + Operator

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
)

Using get_object_vars() and extract()

You can convert the objects to arrays, merge the arrays, and then convert back to an object:

$obj1 = (object) ['name' => 'John', 'age' => 30];  
$obj2 = (object) ['city' => 'New York', 'age' => 35];
...
senior

senior

Gợi ý câu hỏi phỏng vấn

middle

Explain function call by reference

junior

What's the difference between isset() and array_key_exists() ?

middle

What is use of Null Coalesce Operator?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào