Constructor is a special type of function which is used for initialize an object.
In php we use a function called _construct( ). (here double underscore)
You can perform any activities required to instantiate the object.
Php will automatically call this special function when instantiating the object.
You can create objects with the new operator, and then use methods like set_name to set the internal data in that object.
In this way , you can initialize the data inside an object before you start working with that object. If you could both create and initialize an object at the same time? PHP allows you to do that with constructors. Constructor is special methods that automatically run when an object is created.
You pass data to the constructor when you use the new operator to create new objects, and you pass data to the constructor by enclosing that data in parenthesis following the class name. here php constructor , that initialize an object with the name “mahtab”
You can pass many arguments to constructors as you need.
$obj = new Person(“mahtab”, “danish”, “Vikash”);
NOTE :
All php classes come with a default constructor that takes no arguments. It’s the default constructor that gets called when you execute code like this.
$obj = new Person();
$obj->set_name(“mahtab”);
However, as soon as you create your own constructor, no matter how many arguments it takes, the default constructor is no longer accessible.
You can also give the constructor the name of the class. Instead of __construct(). Like this for the Peroson class.
<?php
class Person
{
var $name;
function Person($data)
{
$this->name= $data;
}
}
?>
The __construct( ) function will be automatically invoked when you instantiate a new object of class.
NOTE :-
In php 4 , object constructors were functions with the same name as the class name. but php 5 and php 6 changed this to use a unified constructor scheme. That is called __construct( ). // here __(double underscore)
Trending Tutorials