Skip to content

Complete Tutorials of PHP OOP Constructor with Example code

PHP OOP - Constructor

Constructor in PHP is special type of function of a class which is automatically executed as any object of that class is created or instantiated.

PHP – The __construct Function

PHP 5 allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.

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:

PHP OOP - Constructor

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


OUTPUT : Apple

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

OUTPUT : 
Apple
red

3 thoughts on “Complete Tutorials of PHP OOP Constructor with Example code”

Leave a Reply

Your email address will not be published. Required fields are marked *