Constructor is a special type of function which will be called automatically whenever there is any object created from a class.
Destructor is a special type of function which will be called automatically whenever any object is deleted or goes out of scope.
Syntax:
__construct():
function __construct() {
// initialize the object and its properties by assigning
//values
}
__destruct():
function __destruct() {
// destroying the object or clean up resources here
}
Note: The constructor is defined in the public section of the Class. Even the values to properties of the class are set by Constructors.
Constructor types
Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically.
Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members.
Copy Constructor: It accepts the address of the other objects as a parameter.
Example
<?PHP
class Tree
{
function Tree()
{
echo "Its a User-defined Constructor of the class Tree";
}
function __construct()
{
echo "Its a Pre-defined Constructor of the class Tree";
}
}
$obj= new Tree();
?>
Output:
Its a Pre-defined Constructor of the class Tree
Parameterized Constructor: The constructor of the class accepts arguments or parameters.
The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.
Example -
<?php
class Employee {
Public $name;
Public $position;
function __construct($name,$position) {
// This is initializing the class properties
$this->name=$name;
$this->profile=$position;
}
function show_details() {
echo $this->name." : ";
echo "Your position is ".$this->profile."\n";
}
}
$employee_obj= new Employee("Rakesh","developer");
$employee_obj->show_details();
$employee2= new Employee("Vikas","Manager");
$employee2->show_details();
?>
Output -
Rakesh : Your position is developer
Vikas : Your position is Manager
Constructors start with two underscores and generally look like normal PHP functions. Sometimes these constructors are called as magic functions starting with two underscores and with some extra functionality than normal methods. After creating an object of some class that includes constructor, the content of constructor will be automatically executed.
Note: If the PHP Class has a constructor, then at the time of object creation, the constructor of the class is called. The constructors have no Return Type, so they do not return anything not even void.
Advantages of using Constructors
No comments:
Post a Comment