What is a constructor in PHP?

devquora
devquora

Posted On: Feb 22, 2018

 

Constructor in PHP is a unique function of a class that is automatically executed as any object of that class is created or instantiated and is also called magic function because, in PHP, the magic method starts usually with two underscore characters. In PHP4, we create constructor by class name it means the name of the constructor is the same as the class name but in PHP5, it has been modified to create constructor, it can be initialized by `__construct` keyword.

Since the constructor is a special function and it is automatically called when an object of a class is instantiated, so in that way we can take benefits of constructor by using it in our class. We can set up the object before using it or can start a session in the constructor so we don't have to start in every method of the class. You can write some line of code and start to instantiate an object to call class method then constructor called as the object is instantiated and code which is written in the constructor is executed automatically. Constructor with parameters looks like a regular method because you can pass the variable to the constructor as in regular method.

    Related Questions

    Please Login or Register to leave a response.

    Related Questions

    Appinventiv Php Developer Interview Questions

    How to find datatype of variable in PHP?

    You can find the datatype of a variable in PHP by using the Var_dump() and gettype() functions....

    Appinventiv Php Developer Interview Questions

    What is Interface? Why it is used?

    An interface can be defined as a platform that permits users to develop programs that mention all public methods that need to be implemented by various classes. It does not involve any complexity or d...