n PHP OOP, a constructor is a special method that is automatically called when an object is created. The constructor method is used to initialize an object’s properties with the values passed to it.
Here’s an example of a class with a constructor:
class Person {
public $name;
public $age;
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
public function say_hello() {
echo "Hello, my name is " . $this->name . " and I am " . $this->age . " years old.";
}
}
In this example, the Person
class has two properties ($name
and $age
) and a constructor that takes two parameters ($name
and $age
). The constructor initializes the object’s properties with the values passed to it.
To create an object of the Person
class and initialize its properties using the constructor, we can use the new
keyword:
$person = new Person("John", 25);
This creates a new object of the Person
class and initializes its properties with the values passed to the constructor.
We can then access the object’s properties and methods using the arrow (->
) operator:
echo $person->name; // Output: John
$person->say_hello(); // Output: Hello, my name is John and I am 25 years old.
In summary, the constructor in PHP OOP is a special method that is used to initialize an object’s properties with the values passed to it. It is automatically called when an object is created using the new
keyword.