Loading...

oops in php

Constructor in php

A constructor allows you to initialize an object's properties upon creation of the object.

If you create a __construct() function, PHP will automatically call this function when you create an object from a class.

Notice that the construct function starts with two underscores (__)

<?php
class Student {
  public $name;
 

  function __construct($name) {
    $this->name = $name; 
  }
  function get_name() {
    return $this->name;
  }
}

$student_name = new Student("madhavi");
echo $student_name->get_name();
?>

Output:

madhavi