HOME HTML EDITOR C JAVA PHP

PHP OOP 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 the class.

1. Why Use a Constructor?

Without a constructor, you have to call a "setter" method for every property manually. With a constructor, you can pass values as arguments at the moment of instantiation, saving code and reducing errors.

2. Syntax of __construct()

Notice that the construct function starts with two underscores (__). This is a magic method in PHP.

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

  // The Constructor
  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }

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

// Pass arguments inside the parentheses
$apple = new Fruit("Apple", "red");
echo $apple->get_name();
?>

3. Default Values in Constructors

You can also set default values for constructor parameters. If the user doesn't provide a value, the default one will be used.

<?php
function __construct($name, $color = "unknown") {
  $this->name = $name;
  $this->color = $color;
}
?>

4. Constructor Property Promotion (PHP 8.0+)

In modern PHP, you can define properties directly inside the constructor. This is a shorter way to write the same logic.

<?php
class Fruit {
  // This automatically creates properties and assigns values
  public function __construct(
    public string $name,
    public string $color
  ) {}
}
?>
Pro Tip: Using constructors makes your objects "ready to use" immediately. It ensures that an object cannot exist in an "incomplete" state without its core data.