As we have learn how to declare the class and methods and how to use them. For typical methods first we create the instance of the class and then call the specific method to perform the specific function like this.

here we can see that for calling any function there are two steps first create an instance of class and then call method inside that class.

But there is one method which is automatically called when we create an instance of class , it is called constructor.

Constructor is the built in method it is declared in every class either we write it or not.this is by default.

Use of Constructor

We can understand this by an example, here we take the same classes index.php and CrossLanguage.php and use the constructor inside.The syntax of writing the constructor is same as the other method but the difference is in its name. the name consist of two underscore and suffixed by the keyword ‘construct’ like ”  __construct  “.

This is how we write the CrossLanguage.php.

For index.php previously we have seen that for calling any function there are three steps first we have to include the file second create an instance of class and third is call the specific method. but if we talk about the constructor method then we don’t have to call the constructor method specifically.

we just have to create an instance of class and it is called automatically like this.

now when we call the index.php then it will run the operation inside the constructor method written in CrossLanguage.php.

output

Parameters in Constructors

Parameters can be passed inside the constructor in the same way as we can pass them in any typical method.to understand this consider the following example. Here we first declare 2 variables $name1 and $name2 , and there are two parameters inside the construct method $name3 and $name4. Inside the construct method we assign the local variables to the class variables and use it in echo.

CrossLanguage.php

now in index.php we pass the variables during the creation of instance of the class.

output