There is such a construction:

Class foo{ public $name; function someName() { $model = new foo; $model->name = 'Vasia'; if($this->name != 'Vasia) $this = $model; // В этой сроке и нужно присвоить свойства return $this; } } 

You need to assign all the values ​​of the $model properties to $this , so that you do not explicitly write $this->name = $model->name; for each property $this->name = $model->name;

  • Maybe you still want to initialize the properties of $model from $this and not vice versa? - Dmitriy Simushev
  • @RomanMalcev, how does this function differ from a simple constructor, if it copies the properties of a newly created object of the same class? - splash58

1 answer 1

If you have all public properties, try this:

 foreach(get_class_vars( get_class($model) ) as $prop) { $this->$prop = $model->$prop; } 

UPD In the comments to the question was asked the correct question "Maybe you still want to initialize the properties of $ model from $ this and not vice versa?" (@Dmitriy Simushev). In this case, it will suit you:

 $model = clone $this; 

http://php.net/manual/ru/language.oop5.cloning.php

  • The foreach option suits me, thanks. - Roman Maltsev