Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Constructor

PHP – The __construct Function

A constructor enables the initialization of an object’s properties when the object is created.

When you define a __construct() function, PHP automatically invokes this function when a new object is instantiated from the class.

Note that the constructor function begins with two underscores (__).

In the example below, using a constructor eliminates the need to call the set_name() method separately, reducing the amount of code.

Example

<?php
class Fruit {
  public $name;
  public $color;

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

$apple = new Fruit(“Apple”);
echo $apple->get_name();
?>

Another example:

Example

<?php
class Fruit {
  public $name;
  public $color;

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

$apple = new Fruit(“Apple”“red”);
echo $apple->get_name();
echo “<br>”;
echo $apple->get_color();
?>