How to pass a parameter/variable on the initialization of a PHP class?

Asked

Viewed 529 times

2

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

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

$user = new User($id);

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

1 answer

4


Uses 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 feedback from the database

DEMONSTRATION

  • What does the "protected" ?

  • @Thomsontorvalds protected is to say that only this and the classes that extend this have access to this property, you can put private so that it is only this if you prefer

  • @Thomsontorvalds, I’ve completed a little more to see for sure what you can do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.