Constructor:
Constructor is a special type of function which will be called automatically whenever there is any object created from a class.
//Old (PHP4)
class myClass{
function myClass(){
// Define logic in constructor
}
}
//New (PHP5+)
class myClass{
function __construct(){
// Define logic in constructor
}
}
Note- Old style constructors are DEPRECATED in PHP 7.0, and will be removed in a future version. You should always use __construct() in new code.
Destructor:
Destructor is a special type of function which will be called automatically whenever any object is deleted or goes out of scope.
class myClass{
function __construct(){
// Define logic in constructor
}
function __destruct(){
// this is destructor
}
}
Types of constructors:
- Default constructor
- Parameterized constructor
- Copy Constructor
- Static Constructor
- Private Constructor
A constructor without any parameters is called a default constructor.
A constructor with at least one parameter is called a parametrized constructor.
class Person{
public $name;
public $address;
public function __construct($name){ // parameterized constructor with name argument
$this->name = $name;
}
}
$perObj1 = new Person("Full Stack Tutorials"); // parameterized constructor with name argument
echo $perObj1->name;
//Output:
Full Stack Tutorials
class Person{
public $name;
public $address;
public function __construct($name){ // parameterized constructor with name argument
$this->name = $name;
}
public function __clone(){
}
}
$perObj1 = new Person("Full Stack Tutorials"); // parameterized constructor with name argument
$perObj2 = clone $perObj1; // copy constructor initialize $perObj2 with the values of $perObj1
echo $perObj2->name;
//Output:
Full Stack Tutorials
Purpose of Private Constructor: It ensures that there can be only one instance of a Class and provides a global access point to that instance and this is common with The Singleton Pattern.
class myClass
{
private static $instance;
private function __construct() {
}
public static function get_instance() {
if (!self::$instance)
self::$instance = new myClass();
return self::$instance;
}
}
Comments
Post a Comment