Object-oriented programming in PHP: part 3

PHP

In this third tutorial on object oriented programming in PHP we will talk about the constructor method, we will see what it is and what it is used for. In the previous articles “Object oriented programming in PHP: part 1” and “Object oriented programming in PHP: part 2” we have seen how to create and use a class, an object, a property and a method. We have also said among many things that the class is a model of anything and the object is its practical representation. Going back to the example of the automobile, its class will be the project and the object will be its real physical representation, so from a project of a car I can have infinite cars, these infinite cars can have some common characteristics and some different characteristics. , that is, they may have the same number of gears but may be of a different color or of a different displacement. From this we can say that each object must have specific characteristics of that car it represents. Let’s see a practical example:

<?php
// I create the class
Class Automobile{
  public $numberOfGears = 5;
  public $color;
  public $displacement;
}

// I instantiate the class in three objects
$car1 = new Automobile ();
$car2 = new Automobile ();
$car3 = new Automobile ();

// I'm going to define the properties of the objects
$car1->color= "green";
$car1->displacement = "1200";

$car2->color= "red";
$car2->displacement = "1600";

$car3->color= "blue";
$car3->displacement = "1900";

?>

In the previous example three objects were created from the Automobile class and defined property values such as color and displacement different from each other, leaving only the number of gears common to all (even if this value could have been easily changed at will for each particular object ). So we have three objects of the same family generated by the same model with different characteristics between them.
Another example could be done with a People class that from the same model can generate many objects of type People all different from each other, differentiating for example by name, surname, height, hair color, etc…

The constructor.

Before talking about the manufacturer I would like to make a clarification on the lines written previously. If I had tried to invoke a property in an object without having defined any value, the PHP interpreter would have thrown an exception (an error). If in defining the value of a property I had written the wrong name, for example instead of $ auto1-> color I had written $ auto1-> colors, the PHP interpreter would have added a new color property only and only to $ auto1.
That said, let’s move on to the manufacturer immediately.
To refine the previous code, the defined properties of the individual objects, seen in the listing, can all be written in a single line during the instantiation phase of the class to create the object. The properties should be inserted between the round brackets after the class name, for example like this:

$car2 = new Automobile("red", "1200");

With the property values thus entered, a particular method called __construct () will be automatically called at that time.
That method is a particular method used to construct the object, it is called automatically during the creation of the object and is part of the magic methods.
Now let’s see how it is used:

public function __contruct($color, $displacement)
{
  $this->color = $color;
  $this->displacement = $displacement;
}

And here we have seen how the properties of an object are defined. In summary, we simply pass the values as parameters during the creation of the object, at that moment the magic method __construct () is called which retrieves the parameters, and then they are assigned to the properties defined in the class. Let’s now completely rewrite the first listing using the constructor.

<?php
// I create the class 
Class Automobile{
  public $numberOfGears = 5;
  public $color;
  public $displacement;
  // I define the constructor
  public function __contruct($color, $displacement)
  {
    $this->color = $color;
    $this->displacement = $displacement;
  }
}

// I instantiate the class in three objects
$car1 = new Automobile("green", "1200");
$car2 = new Automobile("red","1600");
$car3 = new Automobile("blue","1900");

?>

The result is a leaner and cleaner code, easier to edit and maintain.
Let’s now highlight a detail. We can put default values between the parameters of the constructor, which in the event that a value is not passed during the construction phase for any reason, we can still have default values that avoid the generation of errors, as in the following example:

public function __construct($color = "yellow")
{
  $this->color=$color;
}

From the previous example, if no color property value is passed to the constructor when creating the object, the yellow value will be assigned by default.

The “magic methods”

Before closing let’s briefly see what PHP magic methods are. The magic methods are special methods that are called automatically by the PHP interpreter upon the occurrence of certain events such as the just seen __construct (). In addition to __construct () there are also others with different functionality that we will see in particular in the next tutorials. The magic methods are recognized that in front of the name they have a double underscore that distinguishes them as for example __construct (), __desctruct (), __get (), __set (), etc…

 

SviluppoMania
StayTuned

MARCO.VERGNANI

Nella mia vita a 12 anni e' entrato a far parte un Intel 80286 con 4MB di RAM, un Hard disk da 20 MB e una primissima scheda VGA appena uscita e da allora mi si e' aperto un mondo pieno di bit. Appassionato di programmazione fin da piccolo, mi diverto a costruire piccoli robottini. Curioso delle molteplici applicazioni che le macchine automatiche possono compiere, e adoro vedere volare quegli strani oggetti chiamati droni.

Related Posts

This site uses Akismet to reduce spam. Learn how your comment data is processed.