How to pass a parameter / variable at startup of a PHP class?

2

How do I initialize a PHP class by passing a parameter at the same time. Same as PDO that is initialized by passing parameters as data for the connection to the database.

In my case I want to simply pass an ID on startup. Ex:

$user = new User($id);

And after passing the parameter using the construct function to load all information from that user, without the need to call some function manually for such an action.

    
asked by anonymous 28.02.2017 / 16:06

1 answer

4

Use a builder :

class User {

   protected $id;
   public $dados;
   public function __construct($id) {
      $this->id = $id; // aqui já tens o teu id
      // echo $this->id; // vai imprimir 4 e podes fazer o que quiseres com ele ao longo dos metodos/atributos desta instância
      // aceder à base de dados, SELECT * FROM users WHERE id = $id, 4 neste caso

      // depois já terás os dados que queres acerca do utilizador
      $this->dados = array('id' => 4, 'nome' => 'Miguel', 'email' => '[email protected]');
   }
}

$u = new User(4);
echo $u->dados['email']; // [email protected]

In this case $dados is just an example of a return of the database information

DEMONSTRATION

    
28.02.2017 / 16:14