Every class must have a constructor [duplicate]

2

I know it's a beginner's doubt, but I need to heal that doubt. I searched the internet and sites do not always come into "agreement".

Does every class need to have a constructor?

Example:

I can make the student class and have no constructor and methods to register (name, age, rm) being this method responsible for providing the values for the properties of the class (name, age, rm) .

In my opinion, this is more practical when instantiating the class. If you just disable the student just calling desativar() .

Because if the constructor gets the properties of the class every time it is to access some method it will have to pass all values (name, age, rm), even if only for desativar() .

Am I thinking wrong? What is the best practice?

    
asked by anonymous 17.08.2015 / 19:18

2 answers

4
  

Does every class need to have a constructor?

No. In PHP, classes can be declared without the definition of a constructor. In the meantime:

  

"Classes that have a constructor method call this method each time a new object is created, so it is appropriate for any startup the object might need before it is used."    PHP: Builders and Destructors

Therefore, it is recommended that you use the constructor to initialize attributes that are commonly bound to all methods of the class.

If the attribute is specific to a method, initialize it at invocation of the method itself.

  

(...)   Because if the constructor gets the properties of the whole class   access to some method of it, I will have to pass all the   values (name, age, rm), even if only to disable ().

I do not fully understand your statement. It is important to understand that whenever a class is instantiated with attributes initialized by the constructor, these properties will be available to any method of the object until it is destroyed.

    
17.08.2015 / 19:38
2

No, no need.

The constructor simply serves to initialize class attributes.

The stdClass class, for example, does not have the __construct method.

In some cases, it is better to have a constructor than to have methods of type mutator and accessor .

Example with constructor:

class Aluno
{
   protected $nome;

   protected $idade;

   public function __construct($nome, $idade)
   {
       $this->nome = $nome; 

       $this->idade = $idade;
   }
}

Example without constructor:

class Aluno
{
   protected $nome;
   protected $idade;

   public function setNome($nome)
   {
      $this->nome = $nome;

   }

   public function setIdade($idade)
   {
      $this->idade = $idade;
   }

}
    
17.08.2015 / 19:20