3. 3
A constructor is a special type non return member function,
that is called automatically when an object is created.
Constructor
Constructor Syntax
function __construct()
{
//construct body
}
5. 5
Constructor
example <?php
class Employee {
public $name, $position;
public function __construct($name,$position)
{
$this->name=$name;
$this->profile=$position;
}
public function show_details() {
echo $this->name." : ";
echo "Position is ".$this->profile;
}
}
$employee_obj = new Employee("Rakesh","developer");
$employee_obj->show_details();
?>
6. 6
Destructor is also a specific member function that is precisely
the opposite of the Constructors method and is called if a
class instance is removed from the memory.
Destructor
Destructor Syntax
function __destruct()
{
//clean up resources here
}
Note: destructor method is called when the PHP code is executed completely by its last line by using PHP exit()
or die()
7. Destructor
example <?php
class Tree
{
public function __construct()
{
echo "Its a Pre-defined Constructor.";
}
public function __destruct()
{
echo "Its a Pre-defined Destructor.";
}
}
$obj = new Tree();
?>
8. Constructors vs Destructors
Constructors Destructors
Accepts one or more arguments. No arguments are passed. Its void.
function name is _construct(). function name is _destruct()
Constructor is involved automatically when the object is created.
Destructor is involved automatically when the object
is destroyed.
Allocates memory. It deallocates memory.
Multiple constructors can exist in a class. Only one Destructor can exist in a class.
Constructors can be overloaded. Destructors cannot be overloaded.
8
9. 9
It is a concept of accessing the features of one class from
another class. If we inherit the class features into another
class, we can access both class properties. We can extends the
features of a class by using 'extends' keyword.
Inheritance
o supports the concept of hierarchical classification.
o PHP supports only single inheritance, where only
one class can be derived from single parent class.
10. Inheritance
example
<?php
class Class_A
{
public function function_A()
{
echo "class A function A";
}
}
class Class_B extends Class_A
{
public function function_B()
{
echo "class B function B";
}
}
$obj= new Class_B();
$obj-> function_A();
?>