PHP OOP - Constructor


PHP - The __construct Function

The builder allows you to launch object layouts when you create an object.

When you create a __construct () function, PHP will call this function automatically when you create an object from the classroom.

Note that construction work starts with two underscores (__)!

We see in the example below, that using a builder saves us from dialing the set_name () method which reduces the code value:


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();
?>