← Back to Chapters

PHP OOP Constructor Function

? PHP OOP Constructor Function

? Quick Overview

In PHP Object-Oriented Programming, the __construct() method is a special function that runs automatically when a new object is created. It prepares the object by initializing its properties.

? Key Concepts

  • Constructor name must be __construct()
  • Executed automatically during object creation
  • Used to initialize class properties

? Syntax & Theory

A constructor is defined inside a class and can accept parameters. These parameters are used to assign values to object properties using the $this keyword.

? Code Example: Basic Constructor

? View Code Example
// Defining a class with a constructor
<?php
class Person {
public $name;
public $age;

public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}

public function introduce() {
return "Hi, I am " . $this->name . " and I am " . $this->age . " years old.";
}
}

$person1 = new Person("Alice", 25);
echo $person1->introduce();
?>

? Constructor with Multiple Objects

? View Code Example
// Creating multiple objects using the same constructor
<?php
class Car {
public $brand;
public $year;

public function __construct($brand, $year) {
$this->brand = $brand;
$this->year = $year;
}

public function getCarInfo() {
return $this->brand . " - Manufactured in " . $this->year;
}
}

$car1 = new Car("Tesla", 2022);
$car2 = new Car("BMW", 2020);

echo $car1->getCarInfo();
echo "<br>";
echo $car2->getCarInfo();
?>

? Live Output / Explanation

Each time a new object is created, the constructor assigns values automatically. This ensures that every object starts in a valid and usable state.

? Use Cases

  • Initializing user profiles
  • Database connection setup
  • Configuring application objects

✅ Tips & Best Practices

  • Always use $this-> to access properties
  • Provide default values when possible
  • Keep constructors simple and focused

? Try It Yourself

  • Create a Book class with title and author
  • Initialize values using a constructor
  • Add a getDetails() method