What is a method " __contruct()"?

Asked

Viewed 7,194 times

7

I am starting studies on POO, and 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>";

?>

Every class will have a constructor method? Why do I need it ?

  • 2
  • This one will, but if you search for "method " __contruct()" there’s nothing objective...@rray

  • @Magichat has no problems. Duplicate questions is good for the site precisely why. Creation of multiple search terms :p

  • No. Every class doesn’t need a constructor method. The community avoids using magical methods like this.

  • In Delphi all classes have a constructor method. We use them when we need to implement something specific, such as feeding some properties during class creation. Another possible thing is to override, overload, and reintroduce this method, when this class inherits from some other class that already implements the constructor. The same applies to the destructor method.

  • @Mauroalexandre didn’t understand what you meant...

  • @Wallacemaxters on which part ?

  • It is not mandatory to have a builder. He, as the name says, is the guy who will build the class. This construction is invoked when you instantiate your class, through the operator new. When there is nothing to build in the class, it is not necessary to use it. It is also worth remembering that builders can be inherited. So you can have a builder in the parent class, but not in the daughter.

  • Yes, sorry. All classes that need to be created will have constructors. For example, the Helpers classes would not have.

  • 3

    @Mauroalexandre ...The community avoids magical methods like this ...... "avoid" in what sense? Almost all classes written in PHP use constructor.

  • Use __contruct() is the most correct way to define a constructor (if you need it) for two reasons, 1: in some very specific situations having a method with the same class name does not guarantee that it is the constructor; 2: in php7 defining a method with the same class name generates a Warning deprecated, that came there from php4

  • 2

    I believe the question is language independent, so I will mark it as a duplicate of this http://answall.com/q/73530/3635 and this http://answall.com/q/81131/3635

  • @Mauroalexandre agree that not every class needs a constructor, the constructor should be used when needed, now what I didn’t understand was "the community avoids", what do you mean by this... builders is a matter of how you will do things, the question is necessity and not avoidance. Could you explain your comment further

Show 9 more comments

3 answers

12


Every class will have a constructor method?

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

In his example, the __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 filling of these attributes must be mandatory, as they are necessary to the class.In this case we can use the __construtor thus:

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 mandatory arguments for the constructor. Then it is necessary to inform them at the time of the class instance, so that the construction occurs as desired:

$person = new Person('Wallace', 26);

The __construtor not necessarily need arguments to work as an initiator, but it will make sense to use it if you have to do something "automatic" at the time of your class instantiation.

Example:

class Document
{
    protected $createdAt;

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

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

 $document = new Document;

 print_r($document);

Upshot:

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 him?

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 this will depend a lot on the architecture of the class created.

There are classes in PHP that do not use constructors, for example stdClass.

$object = new stdClass;

$object->id = 1;

__construct inherited

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

Note 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 Dog inherits an abstract class called Animal. In that case, Animal has a constructor to define the attribute name at the instance. However, I did not need to declare the __construct in Dog, due Animal have these desired functionalities.

Overwriting __construct

In PHP, the __construct may be superscripted by a class inheriting another.

Behold:

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, you completely lose the behavior defined in the parent class (in our case it is the class A).

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

Behold:

class B extends A {  

    protected $argument;

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

}

7

You don’t need it in all classes. Only for classes where you want some action done every time it is instantiated.

When you charge 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 from (this is a crude example, but this is how it works).

You can also pass data into the class via 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 method __destruct, which is called whenever the class is "de-instituted", through a unset($minhaClasse) for example. Although I have never used or seen an application of this in the real world.

See the official PHP documentation for constructors: http://php.net/manual/en/language.oop5.decon.php

3

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 to 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 method __invoke() to invoke the direct parameter:

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

$carro = new Carro();
echo $carro('Direção automática'); 
  • It does not always serve to define parameters. It can also have the functionality to simply initialize internal attributes.

  • You say calling methods internal attributes?

Browser other questions tagged

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