There is a users table in the database, the task: to make a model (MVC) with the ability to select certain table fields.

 users.php class Users { private $id = null; private $login = null; private $password = null; public function __construct($login, $password) { $this->login = $login; $this->password = $password; } // All Setters && Getters for all cells of db // ag public function SetLogin; public function GetLogin static public function getInstance($id) { $row = "SELECT * FROM `users` WHERE `id` = '{$id}' "; if($row){ $obj = new Users($row['login'], $row['password']); $obj->setId($row['id']); return $obj; } } } 

By convention, the users table has many cells, and it is not always necessary to select a record with all the cells, in other words, a request to getInstance needs to be done with certain cells, for example (SELECT login FROM users) ; How, then, to make a call to an object, because the constructor needs all the cells as arguments?

Alternatively, you can pass an array to the constructor, and in the constructor for each property, check the value in the array.

 $this->password = isset($array['password']) ? $array['password'] : null; 

But is there a more concise option?

  • Use fields. The constructor is not needed here. In general, change to any ORM-ku - the need for such classes will disappear immediately. You do not have a model now, but forgive the expression, a piece of the Hindu code. - Sergey Rufanov

1 answer 1

Starting with PHP 5.6, a new syntax is available for functions with an arbitrary number of arguments. In principle, you can use it for your task.

 class Users { private $id = null; private $login = null; private $password = null; public function __construct(...$fields) { $this->login = $fields[0]; $this->password = $fields[1]; } ... } $user = new Users('hello', 'world'); echo "<pre>"; print_r($user); 

However, in this case you depend on the order of the arguments when creating the object. Therefore, your option using a single array argument is the most flexible. An array can be made associative, in this case the order of the elements in the array is not important.

 class Users { private $id = null; private $login = null; private $password = null; public function __construct($fields) { foreach($fields as $key => $value) { $this->$key = $value; } } // ... } $user = new Users(['login' => 'hello', 'password' => 'world']); echo "<pre>"; print_r($user); 

The only thing is that it is better to automate the assignment of variables in the loop, as shown above (if necessary, you can check for a valid array element name, for example, use in_array() to exclude the creation of object variables with an arbitrary name).