This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

7.3 PHP Constructor

    • 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 (__)!
    • We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:
    Example 1: PHP Constructor part 1
    <?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 2: PHP Constructor part 2
    <?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();
    ?>
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon

    Module 6 quiz