What is the role of constructors in initializing variables in PHP classes?

Constructors in PHP classes are special methods that are automatically called when an object of a class is created. They are used to initialize class properties or variables with default values or values passed as arguments during object instantiation. By using constructors, we can ensure that all necessary initialization tasks are performed when an object is created.

class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$person1 = new Person("John Doe", 30);
echo $person1->name; // Output: John Doe
echo $person1->age; // Output: 30