passing class and variable in contruct

0
<?php
   private $pessoa;

   public function __construct(Pessoa $pessoa) {
     $this->pessoa = $pessoa;
   }

How do you get the class Pessoa and a variable? How does this construct get the class Pessoa ??

I am referring to the standard Adapter

    
asked by anonymous 22.03.2018 / 17:34

2 answers

1

In fact, it is receiving a variable of type Person. Since the constructor is asking for an object of Pessoa as a parameter, if anyone is to use the class pass anything else as a parameter, it will automatically receive an error.

Starting with version 7 of PHP you can or can not put types in your variables.

For example, if you want to do a function that must return a int , you can do this:

public function getId(): int{
    return 0;
}

And if you want to get a parameter that must be int , you would do so:

public function setId(int $id){
    $this->id = $id;
}

If you need your parameter to be of type int and you can also receive null , you can put a question mark before the type:

public function setId(?int $id){
    $this->id = $id;
}
    
22.03.2018 / 17:42
0

I believe there must be a confusion of understanding. The above pattern has object-oriented concepts. an object-type variable will receive the attributes of the Person class. example the Person class has the following attributes:

 public class Pessoa
    {
       public string nome { get; set; }
        public int idade { get; set; }
        public char sexo { get; set; }
    }

Then we can create a variable that will store this object with all the attributes

Variable "person" of type "Person" receives null and then is filled.

Pessoa pessoa = null;
       try
        {
             pessoa = new Pessoa ();     //'cria uma instância para Pessoa'
                    pessoa.nome = "Danielle";
                    pessoa.sexo ="F";
                    pessoa.idade= 30;
                    dados.Add(pessoa);
          }

This concept is used for object-oriented programming. It is independent of language. I hope I have helped

    
22.03.2018 / 17:48