passing class and variable in contruct

Asked

Viewed 32 times

0

<?php
   private $pessoa;

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

As in the construction passes the class Pessoaand a variable???... as this variable in the Construct will receive the class Pessoa??

I’m referring to the pattern Adapter

2 answers

1

In fact it is receiving a variable of type Person. As the constructor is asking for an object of the uncle Pessoa as a parameter, if whoever uses the class passes anything else as a parameter, they will automatically receive an error.

Starting from version 7 of PHP you may or may not put types in your variables.

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

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

and if you want to receive 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 the type int and may also receive null, you can put a question mark before the type:

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

0

I believe there must be some confusion of understanding. The above pattern has object-to-object orientation concepts. a variable of the object type will receive the attributes of the Person class. example the Person class has 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

"Person" variable of type "Person" takes null and is then 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. Language-independent. I hope I helped

  • I hope I have helped in your understanding. As I said, the concept of Object Orientation is the same for all languages.

Browser other questions tagged

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