0
0
PHPprogramming~5 mins

Constructor method in PHP

Choose your learning style9 modes available
Introduction

A constructor method helps create an object with initial values automatically when you make it. It saves time and keeps your code neat.

When you want to set up an object with starting information right away.
When you need to make sure some values are always given when creating an object.
When you want to avoid writing extra code to set properties after making an object.
Syntax
PHP
class ClassName {
    public function __construct($param1, $param2) {
        // code to set up the object
    }
}

The constructor method is named __construct with two underscores.

It runs automatically when you create a new object with new ClassName().

Examples
This constructor sets the car's color when you create it.
PHP
<?php
class Car {
    public $color;
    public function __construct($color) {
        $this->color = $color;
    }
}
This constructor sets both name and age for a person object.
PHP
<?php
class Person {
    public $name;
    public $age;
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}
Sample Program

This program creates a Book object with a title and author using the constructor. Then it prints the book's information.

PHP
<?php
class Book {
    public $title;
    public $author;

    public function __construct($title, $author) {
        $this->title = $title;
        $this->author = $author;
    }

    public function getInfo() {
        return "Title: $this->title, Author: $this->author";
    }
}

$myBook = new Book("1984", "George Orwell");
echo $myBook->getInfo();
OutputSuccess
Important Notes

You can have only one constructor method per class.

If you don't write a constructor, PHP uses a default one that does nothing.

Summary

A constructor method sets up an object automatically when created.

It uses the special name __construct.

It helps keep your code clean and easy to use.