Builders in PHP

We see what a constructor is and how to define them in object-oriented programming in PHP.

The constructors are functions, or methods, that are responsible for carrying out the initialization tasks of the objects when they are instantiated. That is, when the objects are created from the classes, a constructor is called that takes care of initializing the object’s attributes and performing any other initialization tasks that are necessary.

It is not mandatory to have a constructor, but they are very useful and are widely used. In the example of the box, which we mentioned in the previous , the normal thing would be to initialize the variables as color or those related to the dimensions and, in addition, indicate that the content of the box is empty. If there is no constructor, none of the object’s attributes are initialized.

The constructor is defined inside the class itself, as if it were another method. The only detail is that the constructor must have the same name as the class. Pay attention to PHP, which differentiates between upper and lower case letters.

For the Box class defined above, you could declare this constructor:

function Box($height=1,$width=1,$length=1,$color=”black”){ $this->height=$height; $this->width=$width; $this->long=$long; $this->color=$color; $this->content=””; }

In this constructor we receive by parameter all the attributes that must be defined in a box.

It is very useful to define some default values ​​in the parameters that the constructor receives, equating the parameter to a value within the parameter declaration of the constructor function, so that, even if the constructor is called without providing parameters, it will be initialized with the values defaults that have been defined.

See also  What are Project Managers

It is important to note that constructors do not have to receive all the values ​​to initialize the object. There are some values ​​that can be initialized to empty or some other fixed value, like in this case the content of the box, which we initially assumed to be empty.

Loading Facebook Comments ...
Loading Disqus Comments ...