Constructors in php

Constructors in php through which a list of arguments following the class name when instantiating an object

$person = new Person(“Fred”, 35);

These arguments are passed to the class’s constructor, a special function that initializes the properties of the class

A constructor is a function in the class called __construct(). Here’s a constructor for the Person class:

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

More Example of constructors in php

class Person
{
 public $name, $address, $age;
 function __construct($name, $address, $age)
 {
 $this->name = $name;
 $this->address = $address;
 $this->age = $age;
 }
}
class Employee extends Person
{
 public $position, $salary;
 function __construct($name, $address, $age, $position, $salary)
 {
 parent::__construct($name, $address, $age);
 $this->position = $position;
 $this->salary = $salary;
 }
}

Leave a Comment