Benefits of using a constructor?

In my search, trying to learn more about OOP in PHP. I have come across a design function many times and simply can no longer ignore it. In my understanding, the constructor is called at the time of creating the object, is this correct?

But why should I create this constructor if I can use the "normal" functions or methods as called?

amuses Kit

+6
constructor oop php
source share
5 answers

Yes, the constructor is called when the object is created.

A small example of constructor utility is

class Bar { // The variable we will be using within our class var $val; // This function is called when someone does $foo = new Bar(); // But this constructor has also an $var within its definition, // So you have to do $foo = new Bar("some data") function __construct($var) { // Assign the $var from the constructor to the $val variable // we defined above $this->val = $var } } $foo = new Bar("baz"); echo $foo->val // baz // You can also do this to see everything defined within the class print_r($foo); 

UPDATE: The question also asked why this should be used, an example of a real life is a database class in which you call an object with a username and password and a table to connect to which the constructor will connect. Then you have the functions to do all the work in this database.

+9
source share

The constructor allows you to make sure that the object is placed in a certain state before you try to use it. For example, if your object has certain properties that are necessary for its use, you can initialize them in the constructor. In addition, constructors allow you to efficiently initialize objects.

+28
source share

The idea of ​​the constructor is to prepare the initial data set for the object so that it can behave normally.

Just call a method not a deal, because you can forget to do it, and it cannot be specified as "required to work" in the syntax, so you will get a "broken" object.

+6
source share
Constructors are good for a lot of things. They initialize the variables in your class. Suppose you create a class BankAccount. $ b = new BankAccount (60); has a constructor that gives the bank account an initial value. They set the variables inside the class basically or can also initialize other classes (inheritance).
+2
source share

The constructor is designed to initialize when an object is created.

You would not want to call an arbitrary method for a newly created object, because this contradicts the idea of ​​encapsulation and requires that the code using this object has an internal knowledge of its internal work (and requires more effort).

+2
source share

All Articles