There is such a code:

<?php // копирование свойств с одинаковыми именами class one { public $a; public $b; } class two { public $a; public $b; } $o = new one; $t = new two; $o->a = 1; $o->b = 2; $t->a = $o->a; $t->b = $o->b; // нужно заменить на одну операцию var_dump($o, $t); ?> 

sandbox

As we see in the end, we have two different objects but with the same property names and their values. I would like to do the same, but without tediously copying the values ​​of one property into a property of another object, provided that the objects have the same properties.

  • Are you motivated by academic interest, or did you just figure out how to solve a particular problem? - rjhdby
  • @rjhdby laziness drives me) I don't want to copy-paste for half an hour. there are two obsalyutno identical classes but just with a very huge number of properties - perfect
  • Well, I already gave the answer, but something tells me that you are eating the wrong sandwich. - rjhdby
  • @rjhdby the thing is that if this sandwich doesn’t eat quickly, then you won’t get a second;) - perfect
  • The second option added - it is more correct - rjhdby

1 answer 1

get_object_vars

 $oVars = get_object_vars($o); $tVars = get_object_vars($t); foreach($oVars as $var => $value){ if(array_key_exists($var, $tVars)){ $t->$var = $value; } } 

Option 2 (better):

Object Iterators

property_exists

 foreach($o as $key => $value){ if(property_exists($t, $key)) { $t->$key = $value; } } 
  • Only in property_exists in the first parameter is not an object, but the class or class name must be transferred - perfect
  • @perfect class Имя класса или объект класса для проверки - rjhdby
  • I understood everything why it didn't work with the object. parental properties do not seem to cling. - perfect
  • You can certainly go completely hellish way through Reflection. I wouldn’t take it, but it’s possible for you :) - rjhdby
  • to know what it is) - perfect