top of page

Posts

What is PHP Constructor?



What are constructors?


A constructor is a method that is always executed when a class is instantiated (made into an object).

An usual method can be called anytime using the arrow function after a class is instantiated, but the constructors are called automatically at the time of instantiation, so there is no process to call them.


Usual Method


$object = new Class Name;
 
$object->Method Name();

Contractor method


$object = new Class Name;

How to write a constructor

You can write constructor like the following


public function __construct() {
  // processing details
}

There is “public” at the beginning, it is one of the access modifiers.


There are “public”, “protected”, and “private”, in this case, it needs to be public otherwise the constructor method will not be invoked when the class is called from the outside.


Also, a method with two underscores "__" in front of the method name is called a magic method. The magic method is a method that is called in special situations and includes "__get" and "__set" in addition to constructors. I got off the topic, but constructors can be written and used as shown above.


Example


Let’s actually use it to have a clear idea. First, create a class. For this time, create a Human class.


class Human
{
  private $name;
  private $age;
  private $from;
 
  public function __construct(
    $name,
    $age,
    $from = 'Japan'
  ) {
    $this->name = $name;
    $this->age = $age;
    $this->from = $from;
  }
}

Since we are creating a human class, we have “name, age, and origin” as necessary properties (variables). When calling this class, the number specified in the constructor arguments must be included in the arguments when creating the instance.


$human = new Human('taro', 32);

By writing the above, the necessary values could be passed to the constructor to instantiate the Human class. The Human class is stored in $human.


Now we have a question.


“ How can it be possible to instantiate a constructor with only two specified arguments even though it is created with three arguments?"


If you look closely at the contents of the constructor, you see that the third argument, $from, is populated with the value “Japan”. Constructors in PHP methods in general can set an initial value in case no value is received. If a value is received, the received value is assigned and no initial value is invoked.


The reason why private was specified for the variable is that it prohibits direct modification of the variable from the outside. This way of writing is called encapsulation.


You may ask “What is wrong with changing directly from outside?”.


For example, for the age variable, you want to set a maximum value up to 200 years old, but if you allow direct modification, it can also include values over 201 years old. Therefore, encapsulation is always used, and a value assigned to a variable after checking whether the value is invalid or not via a method or other condition to determine whether the value is invalid.


In this case, a set method with an invalidation expression is created and by calling the set method with the constructor, setAge() is called when the Human class is instantiated to limit the value that goes into $age.


In the following method, when it receives a value of 201 or higher, a value 200 is forced to assign.



class Human
{
  private $name;
  private $age;
  private $from;
  
    public function __construct(
    $name,
    $age,
    $from = 'Japan'
  ) {
    $this->name = $name;
       $this->setAge($age);
    $this->from = $from;
  }
 
  public function setAge($age) {
        if ($age <= 200) {
            $this->age = $age;
        } else {
            $this->age = 200;
        }
    }
}

The benefit of using constructor.


The variables being initialized in the constructor, means that the variables of the newly created instance will always have the specified value. This feature allows variables to have per-object values.




This blog post is translated from a blog post written by Ryu Matsuki on our Japanese website Beyond Co..


Commentaires


bottom of page