What is a "__contruct ()" method?

5

I'm starting studies on OOP, and I came across the following method:

<?php
class ShopProduct
{
    public $title = "default product";
    public $producerMainName = "main name";
    public $producerFirstName = "first name";
    public $price = 0;
    function __construct($title, $firstName, $mainName, $price)
    {
        $this->title = $title;
        $this->producerFirstName = $firstName;
        $this->producerMainName = $mainName;
        $this->price = $price;
    }
    function getProducer()
    {
        return "{$this->producerFirstName}"."{$this->producerMainName}";
    }
}

$product1 = new ShopProduct("1atributo", "2atributo", "3atributo", 7);
print "author: {$product1->getProducer()}"."</br>";

?>

Will every class have a constructor method? Why do I need it?

    
asked by anonymous 16.11.2016 / 14:03

3 answers

6
  

Will every class have a constructor method?

Not necessarily. A constructor is responsible for initializing the class in the act of instantiation. That is, when the new operator is invoked together with the class name, __construct is implicitly called to do the operations you defined on it.

In your example, __construct is being used to pass arguments to your class and store it in properties.

A small example for you to understand is a class where you have Getters and Setters to set values to a property. However, the fills of these attributes need to be mandatory, as they are required by the class. In this case we can use __construtor as follows:

class Person
{
    protected $name;
    protected $age;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }

    /**
     * Gets the value of name.
     *
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Sets the value of name.
     *
     * @param mixed $name the name
     *
     * @return self
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Gets the value of age.
     *
     * @return mixed
     */
    public function getAge()
    {
        return $this->age;
    }

    /**
     * Sets the value of age.
     *
     * @param mixed $age the age
     *
     * @return self
     */
    public function setAge($age)
    {
        $this->age = $age;

        return $this;
    }
}

Note that $name and $age are arguments required for the constructor. Then it is necessary to inform them at the moment of the instance of the class, so that the construction occurs as desired:

$person = new Person('Wallace', 26);
The __construtor does not necessarily need arguments to work as a initializer, but it will make sense to use it if you have to do something "automatic" at instantiation of your class.

Example:

class Document
{
    protected $createdAt;

    public function __construct()
    {  
        $this->createdAt = new \DateTime;
    }
}

If you instantiate your class, note that it will automatically create the DateTime object in the createdAt property.

 $document = new Document;

 print_r($document);

Result:

Document Object
(
    [createdAt:protected] => DateTime Object
        (
            [date] => 2016-11-16 11:31:42.000000
            [timezone_type] => 3
            [timezone] => America/Sao_Paulo
        )

)
  

Why do I need it?

As stated earlier, to be able to define what will be done when the class was instantiated.

Of course you may not need it in some cases, but it will depend a lot on the architecture of the class you created.

There are classes in PHP that do not use constructors, such as stdClass .

$object = new stdClass;

$object->id = 1;

% inherited%

There will be cases where you will not need to declare the constructor in the class because it has an inheritance from another that already has a constructor.

Look at the example below:

abstract class Animal
{
    protected $name;

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

    public function getName()
    {
        return $this->name;
    }

    abstract public function getSound();

}

class Dog extends Animal{

    public function getSound()
    {
        return 'au au';
    }
}

$dog = new Dog('Billy');

$dog->getName(); // 'Billy'

Note that __construct inherits an abstract class called Dog . In this case, Animal has a constructor to set the Animal attribute to the instance act. But I did not have to declare the name in Dog, because%% has these desired features.

Overwriting __construct

In PHP, Animal can be overwritten by a class that inherits another.

See:

class A{

    protected $argument;

    public function __construct() {

         echo "chamei a classe A";
    }
}


class B extends A {  

    protected $argument;

    public function __construct($argument)
    {
       echo "chamei a classe B com argumento $argument";
    }

}

new A(); // "Chamei a classe A"
new B('oi'); // "Chamei a calsse B com argumento oi"

Important note is that when you override the constructor, it completely loses the behavior defined in the parent class (in our case it is the __construct class).

In this case, if you need to define a constructor for the Daughter class, but need to call the parent class constructor, you can use __construct to resolve this problem.

See:

class B extends A {  

    protected $argument;

    public function __construct($argument)
    {
        parent::__construct();
        echo "chamei a classe B com argumento $argument";
    }

}
    
16.11.2016 / 14:20
6

You do not need it in all classes. Only for classes where you want action to be taken every time it is instantiated.

When you instantiate the class $minhaClasse = new MinhaClasse() the constructor method is called, if it is registered in the class. You could for example record a log that that class was instantiated (this is a rough example, but that's how it works).

You can also pass data into the class through the constructor method. function __construct($nome, $idade) and when you try to instantiate the class you will have to pass the variables into it: $minhaClasse = new MinhaClasse("Rafael", 25) .

There is also the __destruct method, which is called whenever the class is "de-emphasized", by unset($minhaClasse) for example. Although I have never used or seen an application of this in the real world.

See the official PHP builder documentation: link

    
16.11.2016 / 14:19
1

Not every class needs a constructor method. The constructor is basically for you to start a class, eventually it is possible to set input parameters for this initialization, as well as call internal methods. It never returns values:

class Carro
{
     private $direcao; //atributo da classe

     public function __construct($param) //parâmetro de entrada
     {
         $this->direcao = $param; //seta o parâmetro de entrada
     }

     public function getDirecao() //retorna o que foi setado no construtor
     {
         return "Direção ".$this->direcao;
     }

}

$carro = new Carro('automática');
echo $carro->getDirecao(); //imprime o retorno do que foi setado

To return, you can also use the __invoke() method to invoke the direct parameter:

class Carro {
   public function __invoke($param) {
      return $param;
   }
}

$carro = new Carro();
echo $carro('Direção automática'); 
    
16.11.2016 / 15:00