Method_constructed with an uncertain number of arguments



  • A table users In the database, the challenge is to make a model (MVC) with a sample of certain fields of the table.

    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
    // a.g 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;
         }
    }
    

    }

    Table users has a lot of cells, and you don't always have to make a sample of the records with all the cells, that is, a request for information. getInstance You have to do with certain cells, for example. (SELECT login FROM users); How do you call the target, because the designer needs all the cells as arguments?

    As an option for the designer to transmit the mass, and for each characteristic the design can verify the value in the mass.

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

    But is there a more concise option?



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

    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 manner in which the arguments are followed in establishing the facility. Therefore, your option, using one Massive argument, is the most flexible. Massive may be associated, in which case the sequence of elements in the mass will not be 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, better automate the classification of variables in the cycle, as shown above (if necessary, a validation for the permissible name of the mass element, e.g., use) in_array()in order to prevent the establishment of a variable object with an arbitrary name.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2