I describe the Login method in the user model. The result of an email search query is an object of class User. Accordingly, if the password hashes match, I would like to record all the properties of the found object in the current object, and return it as the result of the method. Something like $this = $result; return $this; $this = $result; return $this;

 public function login($email, $password) { $sql = 'SELECT * FROM user WHERE email = :email'; $db = new Db(); $result = $db->query($sql, self::class, [':email' => $email])[0]; if (password_verify($password, $result->getPassword())) { //Как здесь записать в текущий объект все свойства объекта $result? return $this; } else { $error = 'Неправильная пара логин\пароль'; return $error; } } 
  • Write down clearly. It is possible with foreach through the list of fields. Any kind of magic will only make it worse (readability, support, debugging). - vp_arth

2 answers 2

Solution with copying object properties:

 class User implements \JsonSerializable { private $username; private $password; private $name; private static function findByUsername($username) { $res = new self(); $res->username = $username; $res->name = 'Some User'; $res->password = password_hash("aXSA9_5uZp0QLhGY", PASSWORD_DEFAULT); return $res; } public function login($username, $password) { $user = self::findByUsername($username); if (password_verify($password, $user->password)) { $fields = get_object_vars($user); foreach ($fields as $field => $value) { $this->$field = $value; } } } public function jsonSerialize() { return [ 'username' => $this->username, 'name' => $this->name ]; } } $user = new User(); $user->login('admin', 'aXSA9_5uZp0QLhGY'); echo json_encode($user); // {"username":"admin","name":"Some User"} 

The key is getting object properties using get_object_vars .
Demonstration

    Judging by the fact that in your method there are no necessary references to $ this - the method claims to become static.

    From the static method, you can simply return a fresh object:

     public static function login($email, $password): User { $sql = 'SELECT * FROM user WHERE email = :email'; $db = new Db(); // todo: extract concrete class usage $users = $db->query($sql, self::class, [':email' => $email]); if (!empty($users) && password_verify($password, $users[0]->getPassword())) { return $users[0]; } throw new AuthException('Неправильная пара логин\пароль'); } 
    • Thanks for the answer, I agree with you about the static method. But still, I was wondering how to write the data of a fresh object into the properties of the current one. - Roman Andreev