OOP Constructor

Last updated on

In PHP Object-Oriented Programming (OOP), constructor is like the welcome committee for every new object you create. It is there to get everything in place the moment an object is born, handling the initial setup so that your code is organized from the start.

Let's get started.

What is a Constructor?

A constructor in PHP is a method that automatically kicks in the moment you create a new instance of a class. It is called __construct(), and whenever you create an object, PHP looks for this method and runs it right away. This is where you can set up initial values or handle any quick tasks needed to get the object ready to go.

Here’s a simple example to show how a constructor works:

class Car {
    public $brand;

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

$myCar = new Car("Toyota");
echo $myCar->brand; // Outputs: Toyota

In this code, $myCar gets the brand “Toyota” assigned immediately as it is created. You do not have to do any extra work to set the brand—it is all handled by the constructor as soon as the object is created.

So, why do we need to use constructors in PHP? Let's find the answer in the following section.

Why Use Constructors?

Constructors are super helpful whenever you want each object to start with certain settings or values. So, if you have a User class, and every user has a role, like “member” or “admin.” A constructor lets you handle that setup right away. This means you do not have to add extra lines to set up the role after creating each object.

Putting all the setup in one place—the constructor—saves you time and keeps your code consistent.

Every instance of the class starts off in the right state without any additional steps.

In the following section, you will understand how to setting default values with constructors in PHP.

Setting Default Values with PHP Constructor

Let’s say you are building a User class, and you want each user to start off with a default role of “member” unless specified otherwise. You can set that up right in the constructor.

here is an example:

class User {
    public $name;
    public $role;

    public function __construct($name, $role = "member") {
        $this->name = $name;
        $this->role = $role;
    }
}

$user1 = new User("Alice");
echo $user1->role; // Outputs: member

$user2 = new User("Bob", "admin");
echo $user2->role; // Outputs: admin

Here, if you do not provide a role, the constructor automatically sets it to “member.” But if you do pass a role, like “admin” for Bob, it uses that instead. This keeps things flexible and keeps you from writing extra setup code every time.

Let's move on to the below section to learn how to add logic in constructors in PHP.

Adding Logic to OOP Constructor in PHP

Constructors are not just for setting basic properties; you can also add simple logic to make sure objects start with valid values. Let’s say you have a Product class where every product needs a price, but you want to make sure it is not negative. You can add a quick check in the constructor.  

class Product {
    public $price;

    public function __construct($initialPrice) {
        $this->price = $initialPrice > 0 ? $initialPrice : 0;
    }
}

$product = new Product(-20);
echo $product->price; // Outputs: 0, since negative price is reset to 0

With this setup, if someone tries to set a negative price, the constructor automatically resets it to zero. This way, you do not have to worry about invalid prices popping up later on.

Wrapping Up

Constructors in PHP OOP are a great way to handle setup quickly and consistently. They let you initialize your objects with all the values and settings they need from the very start, so you do not have to keep adding extra setup steps each time. This keeps your code cleaner and easier to work with, especially when you are dealing with objects that have specific initial requirements.

If you need to see more PHP tutorials, click here. Thank you for reading.

Frequently Asked Questions (FAQs)

  • What is a constructor in PHP?

    A constructor in PHP is a special method called __construct() that runs automatically when a new object of a class is created. It allows you to set up initial values or handle any required tasks right when the object is born.
  • How do I define a constructor in PHP?

    You define a constructor using the __construct() method within a class. Here’s an example:
    class Car {
        public $brand;
        public function __construct($brand) {
            $this->brand = $brand;
        }
    }
    $myCar = new Car("Toyota");
    echo $myCar->brand; // Outputs: Toyota
  • Why should I use a constructor in PHP?

    Constructors help to initialize objects with specific values right away, so you don’t have to set them manually each time you create an instance. This keeps your code organized and reduces redundancy.
  • Can I set default values with a PHP constructor?

    Yes, you can set default values directly in the constructor’s parameters. For example, setting a default role for a User class:
    class User {
        public $name;
        public $role;
        public function __construct($name, $role = "member") {
            $this->name = $name;
            $this->role = $role;
        }
    }
    $user1 = new User("Alice");
    echo $user1->role; // Outputs: member
    $user2 = new User("Bob", "admin");
    echo $user2->role; // Outputs: admin
  • Can I add logic to a PHP constructor?

    Yes, constructors can include logic for validating or modifying initial values. For instance, setting a minimum price in a Product class:
    class Product {
        public $price;
        public function __construct($initialPrice) {
            $this->price = $initialPrice > 0 ? $initialPrice : 0;
        }
    }
    $product = new Product(-20);
    echo $product->price; // Outputs: 0
  • What happens if I don’t define a constructor in my PHP class?

    If you don’t define a constructor, PHP will simply create the object without any custom setup. You’ll need to manually set any necessary properties after creating the object.
  • Can a class have more than one constructor in PHP?

    , PHP does not support multiple constructors. However, you can work around this limitation by using default parameter values or by defining different setup methods.
  • How do I call a parent constructor in a child class in PHP?

    To call a parent constructor from a child class, you use parent::__construct(). Here’s an example:
    class Vehicle {
        public $type;
        public function __construct($type) {
            $this->type = $type;
        }
    }
    class Car extends Vehicle {
        public $brand;
        public function __construct($type, $brand) {
            parent::__construct($type);
            $this->brand = $brand;
        }
    }
    $myCar = new Car("Sedan", "Toyota");
    echo $myCar->type; // Outputs: Sedan
    echo $myCar->brand; // Outputs: Toyota
Share on: