Types of Constructor in PHP
A constructor in PHP is a special method that runs automatically when an object is created. It helps set initial values and prepare the object for use. PHP mainly has three types of constructors:
- Default Constructor
- Parameterized Constructor
- Copy Constructor
Default Constructor
A default constructor is a constructor without any parameters. It runs automatically when you create an object and is used to set default values or display a message.
Example:
<?php
class Student
{
// Default constructor
public function __construct()
{
echo "A new student is created!<br>";
}
}
// Creating an object
$student1 = new Student(); // Constructor runs automatically
?>
Explanation:
- The constructor runs when
$student1is created. - No parameters are passed; it just prints a message.
Parameterized Constructor
A parameterized constructor accepts parameters to initialize object properties. It’s useful when you want to pass values during object creation.
Example:
<?php
class Student
{
public $name;
public $age;
// Parameterized constructor
public function __construct($name, $age)
{
$this->name = $name; // Set name
$this->age = $age; // Set age
echo "Student $name is $age years old. <br>";
}
}
// Creating objects with parameters
$student1 = new Student("Raj", 20);
$student2 = new Student("Simran", 22);
?>
Explanation:
$nameand$ageare passed as arguments.- The constructor sets the object’s properties.
Copy Constructor (Simulated in PHP)
PHP does not have a built-in copy constructor, but you can simulate it by creating a constructor that copies properties from another object.
<?php
class Student
{
public $name;
// Parameterized constructor
public function __construct($name)
{
$this->name = $name;
}
// Copy constructor (simulated)
public static function copy(Student $student)
{
return new Student($student->name);
}
}
// Create original object
$student1 = new Student("Raj");
// Create copy using the copy constructor
$student2 = Student::copy($student1);
echo "Original: $student1->name<br>"; // Raj
echo "Copy: $student2->name<br>"; // Raj
?>
Explanation:
copy()takes anotherStudentobject and creates a new one with the same data.- Both objects have the same name but are independent.