EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Constructor in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Constructor in PHP

Constructor in php

Introduction to Constructor in PHP

The constructor is the PHP5 OOP (Object Oriented Programming) concept. The constructor is associated with the classes we declare in the program. The constructor is called automatically when the object of the class is instantiated, thus the definition of constructor goes like this, “A constructor is a special method which is called automatically when the object of the class is instantiated”. In this topic, we are going to learn about constructors in PHP.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

<?php
Class Classname {
//constructor
function __construct() {
//statements
}
}
?>

In the above piece of code, the constructor begins with an __ double underscore followed by the keyword construct. A constructor without __construct() or in case the name of the class is changed then the method defined is just a method and not a constructor. Thus it is important to define the constructor in a class as per the syntax defined.

Types of Constructor

Here are some of the types of Constructor with their output given below

1) Pre-defined Constructor

To clarify about Pre-defined Constructor, Let us look at an example given below

Example of Pre-defined Constructor

Code:

<?php
class Person {
function  CanSpeak() {
echo " Not a constructor method " . '<br>';
}
function __construct() {
echo " In the constructor method " . '<br>';
}
}
//Object of class calling the constructor internally
$p = new Person();
// Object of class calling the normal method
$p->CanSpeak();
?>

Output:

Output 1

In the above example

We have a class Person, which has two methods, where a person CanSpeak() Method and the constructor method __construct(). Next, we have instantiated the class as an object $p. Using the $p we have called the normal method.  As soon as the object is created the constructor method is called and the statement inside the method is executed, similarly further the CanSpeak() method which is a normal method and not a constructor method is called using the same object $p and the statement inside that method is executed. Also, since the constructor defined above does not have any arguments we will call it a zero-argument constructor or predefined constructor.

2) Parameterized Constructor

A constructor can be with or without arguments. The constructor with arguments is called the parameterized constructor and the constructor without arguments is called the zero-argument constructor. Let us look at an example.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example of Parameterized Constructor

Code:

class Person {
private $first;
private $email;
private $mobile;
public function __construct($name, $email, $mobile) {
echo "Initialising the object...<br/>";
$this->name = $name;
$this->email = $email;
$this->mobile = $mobile;
}
public function showProfile() {
echo "My name is: " . $this->name. " " . $this->email. " " . $this->mobile;
}
}
$john = new Person("John","John@gmail.com", "9187986786");
$john->showProfile();

Output:

Output 2

How does Constructor Work?

Let us take a look at the base class constructor and derived class which extends the base class using the extends keyword which has its own constructor to execute and the parent constructor to execute as well. Till now we learned only about the constructor declared in a class. Let us add some more knowledge to the constructor here. With the following example, the base class Person has a constructor, now this constructor is called by the derived class or the Sub Class by using parent keyword and thus can access the Base Class Person’s constructor.

The Output flow

First, the Person constructor is called, then the Customer constructor is called which internally calls again the Person constructor and then its own customer constructor and last the Employee class which extends the Person class thus the Person constructor is called again.

Code:

class Person {
function __construct() {
echo "In Person constructor"."<br>";
}
}
class Customer extends Person  {
function __construct() {
parent::__construct();
echo "In Customer constructor"."<br>";
}
}
class Employee extends Person  {
// inherits Person’s constructor
}
// In Person constructor
$p = new Person();
// In Person constructor
// In Customer constructor
$c = new Customer();
// In Employee constructor
$e = new Employee();

Output:

Constructor in PHP -Output flow

In the below example we have shown how the set method and the get method works. Using the encapsulation concept in OOP. Initially, the program is declared with a constructor, a set_name method and a get_name method. Note that the constructor is a parameterized constructor which is definitely called when the class is instantiated and therefore the first output is John Doe next created an object of the class and called the set_name and get_name methods which print the output as Alice.

Code:

<?php
class Person {
public $name;
function __construct($name) {
echo $this->name = $name;
}
function set_name($name) {
$this->name = $name;
}
function get_name() {
echo $this->name;
}
}
// In Person constructor
$p = new Person('John Doe');
echo "\n";
$p->set_name('Alice');
$p->get_name();
?>

Output:

Output 4

The Access Specifier

There are three access specifier in PHP

  • Public
  • Protected
  • Private

Public: Members of the class declared as public are accessible everywhere.

Protected: Members of the class declared as protected are accessible only within the base class and the derived class which extends the base class.

Private: Members of the class declared as private are accessible with the class that defines it.

Also, the variables declared are called data members or properties and the functions declared are called as data methods. In the below example we have Base Class declared as Person which has the following properties along with the access specifiers public name, protected email and private mobile. Now the class is instantiated with an object $p and these three properties which are accessed from the object. which outputs are an error, why because, the protected property says that protected are accessible only within the base class and the derived class which extends the base class?

Code:

<?php
class Person {
public $name=;
protected $email;
private $mobile;
function __construct() {
print "In Person constructor";
}
}
// In Person constructor
$p = new Person();
echo $p->name;
echo $p->email;
echo $p->mobile;
?>

Output:

Constructor in PHP -Access Specifier

Conclusion

Hope this article finds you what you have been searching for. The article has different examples for you to learn. The more you put the examples in practice the easier it will become to grasp.

Recommended Articles

This is a guide to Constructor in PHP. Here we have discussed the basic concept with types of constructor and how does the Constructor in PHP works. You may also look at the following article to learn more –

  1. What is PHP?
  2. PHP String Functions
  3. Layout in Java
  4. Public Function in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More