PHP Constructor
A constructor is a special method in a class that is automatically called when an object is created. It is used to initialize object properties and perform any setup tasks.
Defining a Constructor
<?php
class Person {
public $name;
// Constructor
public function __construct($name) {
$this->name = $name;
}
public function greet() {
return "Hello, my name is " . $this->name . ".";
}
}
?>
Using the Constructor
<?php
$person = new Person("Alice");
echo $person->greet();
?>
Output:
Hello, my name is Alice.
Explanation: This example demonstrates how to define a constructor in a class and how it initializes the object's properties when the object is created.