Google News
logo
PHP program to Creating a Constructor
In the following example of how to create a constructor in PHP :
Program :
<?php
class Person {
  public $name;
  public $age;

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

$person1 = new Person("John", 25);
echo $person1->name . " is " . $person1->age . " years old.";
?>
Output :
John is 25 years old.
In this example, we define a `Person` class with two properties, `$name` and `$age`. We then define a constructor method using the `__construct()` function, which takes in two parameters `$name` and `$age`. Inside the constructor, we assign the values of these parameters to the respective class properties using the `$this` keyword.

We then create a new instance of the `Person` class, passing in the values "John" and 25 as arguments to the constructor.

Finally, we use the `echo` statement to output the person's name and age.