In PHP Object-Oriented Programming, the __construct() method is a special function that runs automatically when a new object is created. It prepares the object by initializing its properties.
__construct()A constructor is defined inside a class and can accept parameters. These parameters are used to assign values to object properties using the $this keyword.
// Defining a class with a constructor
<?php
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function introduce() {
return "Hi, I am " . $this->name . " and I am " . $this->age . " years old.";
}
}
$person1 = new Person("Alice", 25);
echo $person1->introduce();
?>
// Creating multiple objects using the same constructor
<?php
class Car {
public $brand;
public $year;
public function __construct($brand, $year) {
$this->brand = $brand;
$this->year = $year;
}
public function getCarInfo() {
return $this->brand . " - Manufactured in " . $this->year;
}
}
$car1 = new Car("Tesla", 2022);
$car2 = new Car("BMW", 2020);
echo $car1->getCarInfo();
echo "<br>";
echo $car2->getCarInfo();
?>
Each time a new object is created, the constructor assigns values automatically. This ensures that every object starts in a valid and usable state.
$this-> to access propertiesBook class with title and authorgetDetails() method