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";
}
}
Related: What good is a builder?
– rray
This one will, but if you search for "method " __contruct()" there’s nothing objective...@rray
– MagicHat
@Magichat has no problems. Duplicate questions is good for the site precisely why. Creation of multiple search terms :p
– Wallace Maxters
No. Every class doesn’t need a constructor method. The community avoids using magical methods like this.
– Mauro Alexandre
Related: Every class needs a builder?
– Wallace Maxters
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.
– Victor Tadashi
@Mauroalexandre didn’t understand what you meant...
– Wallace Maxters
@Wallacemaxters on which part ?
– Mauro Alexandre
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.– Wallace Maxters
Yes, sorry. All classes that need to be created will have constructors. For example, the Helpers classes would not have.
– Victor Tadashi
@Mauroalexandre ...The community avoids magical methods like this ...... "avoid" in what sense? Almost all classes written in PHP use constructor.
– Wallace Maxters
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– rray
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
– Guilherme Nascimento
@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
– Guilherme Nascimento