Advertisement
  1. Code
  2. Coding Fundamentals
  3. OOP

Understanding PHP Constructors

Scroll to top

In this article, we're going to discuss the basics of constructors in PHP. You'll learn the purpose of PHP constructors and how to use them.

What Is a Constructor?

Here's the official definition:

Constructors are ordinary methods which are called during the instantiation of their corresponding object. As such, they may define an arbitrary number of arguments, which may be required, may have a type, and may have a default value. Constructor arguments are called by placing the arguments in parentheses after the class name. PHP Manual: Constructors and Destructors

When you instantiate an object of any class, and if that class has defined the constructor method, it will be automatically called. If the constructor method has defined any mandatory arguments, you must pass those arguments as well when you instantiate an object of that class.

Let’s quickly see what a constructor method looks like in PHP.

1
<?php
2
class tutsplus {
3
    public function __construct()
4
    {
5
       // you can initialize object properties here

6
       echo 'Hey, you have just instantiated a new object!';
7
    }
8
}
9
10
$objTutsplus = new tutsplus();
11
// output: Hey, you have just instantiated a new object!

12
?>

So that’s how you can define a constructor in your class. You must define the __construct method in your class, and it becomes the constructor method for your class. In the above example, whenever you instantiate the tutsplus object, the __construct method will be called first. It’s important to note that you must define a constructor method as public, or you won't be able to instantiate an object of your class!

Prior to PHP 5, to define a constructor, you would use a function with the same name as the class it is defined in, and it would be treated as a constructor method! You might be familiar with this way of declaring constructors from other programming languages like C++. In PHP, they are called PHP4-style constructors, and it’s not recommended to use this style, since they are going to be deprecated sooner or later.

Let’s revise the previous example to see how the constructor would look in a previous version of PHP:

1
<?php
2
class tutsplus {
3
    public function tutsplus()
4
    {
5
        // you can initialize object properties here

6
        echo 'Hey, you have just instantiated a new object!';
7
    }
8
}
9
10
$objTutsplus = new tutsplus();
11
// output: Hey, you have just instantiated a new object!

12
?>

At the time of writing, this example still worked. Try it out! 

What’s the Purpose of a Constructor?

Now you know how to declare a constructor method in PHP, but what is the use of a constructor method? That’s what we’ll discuss in this section, with a couple of real-world examples.

Initializing Required Properties

The main purpose of a constructor method is to initialize an object's properties when it’s being created. The benefit of this approach is that you don’t have to call setter methods later on to initialize the object's properties after an object is created. So if you think that an object must have a few properties set, a constructor method is the way to go!

Let’s quickly go through the following example to understand how it works. 

1
<?php
2
class tutsplusAuthor
3
{
4
    private $author_name;
5
    private $author_email;
6
7
    public function __construct($name, $email)
8
    {
9
        $this->author_name = $name;
10
        $this->author_email = $email;
11
    }
12
13
    public function getAuthorName()
14
    {
15
        return $this->author_name;
16
    }
17
18
    public function getAuthorEmail()
19
    {
20
        return $this->author_email;
21
    }
22
}
23
24
$objTutsplusAuthor = new tutsplusAuthor("John", "john@tutsplus.com");
25
echo $objTutsplusAuthor->getAuthorName();
26
echo $objTutsplusAuthor->getAuthorEmail();
27
?>

As you can see, when the tutsplusAuthor object is instantiated, the __construct method is called. The __construct method expects two arguments, and we’ve passed those two arguments when we create the new object: new tutsplusAuthor("John", "john@tutsplus.com"). Finally, we’ve initialized the author_name and author_email properties to the corresponding values that are passed in the __construct method. So in this way, you can initialize object properties with a constructor method.

If you tried to instantiate the tutsplusAuthor object without passing any arguments, you would get a fatal error, as shown in the following snippet.

1
<?php
2
// try to instantiate tutsplusAuthor without arguments

3
$objTutsplusAuthor = new tutsplusAuthor();
4
// output

5
// PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function tutsplusAuthor::__construct(), 0 passed in /public_html/examples/constructor.php on line 24 and exactly 2 expected in /public_html/examples/constructor.php

6
?>

So you need to make sure that you pass any required arguments when you instantiate the tutsplusAuthor object.

Type-Checking Constructor Arguments

In fact, you can also do type checking if you want to ensure that the arguments are of specific types.

1
<?php
2
class tutsplusAuthor
3
{
4
    ...
5
    ...
6
    public function __construct(string $name, string $email, array $hobbies)
7
    {
8
        $this->author_name = $name;
9
        $this->author_email = $email;
10
        $this->hobbies = $hobbies;
11
    }
12
    ...
13
    ...
14
}

In the above example, you must pass the first two arguments of type string, and the last argument must be of type array. If you passed a string value in the last argument, you would get the following error:

1
PHP Fatal error:  Uncaught TypeError: Argument 3 passed to tutsplusAuthor::__construct() must be of the type array, string given

So that’s how you can do strict type checking with constructor arguments.

Initializing a Database Connection

Another use of a constructor is to do some I/O: for example, opening a file and starting to read its contents, beginning an API request, or creating a database connection.

Let’s look at an example of a constructor that creates a database connection.

1
<?php
2
class Database
3
{
4
    private $host;
5
    private $user;
6
    private $password;
7
    private $dbname;
8
    private $connection;
9
10
    public function __construct($host, $user, $password, $dbname)
11
    {
12
        $this->host=$host;
13
        $this->user=$user;
14
        $this->password=$password;
15
        $this->dbname=$dbname;
16
17
        $this->connection = mysqli_connect($this->host, $this->user, $this->password, $this->dbname);
18
19
        if (!$this->connection) {
20
            die("connection failed: " . mysqli_connect_error());
21
        }
22
    }
23
24
    // other DBAL methods

25
}
26
?>

How to Call a Constructor of the Parent Class

In this last section, we’ll see how you can call parent class constructors. If you are aware of the concept of inheritance, you'll know that a class can extend another class to build on its functionalities.

Now, there’s a possibility that both child and parent classes have their own constructors. So how would you call the constructor of the parent class when a child class object is being instantiated?

Let’s try to understand it with an example.

1
<?php
2
class Person
3
{
4
    private $name;
5
6
    public function __construct($name)
7
    {
8
        $this->name=$name;
9
    }
10
}
11
12
class Employee extends Person
13
{
14
    private $employee_id;
15
16
    public function __construct($name, $employee_id)
17
    {
18
        parent::__construct($name);
19
        $this->employee_id=$employee_id;
20
    }
21
}
22
$obj=new Employee('John', 'J123');
23
?>

As you can see, the Employee class extends the Person class. Now, when the Employee object is instantiated, the __construct() method of the Employee class is called. In this method, we’ve used the special parent keyword to call the __construct() method of the parent class. And thus, it would end up calling the __construct() method of the Person class. It’s always a good practice to call the __construct() method of the parent class if your class extends any class.

Conclusion

Today, we discussed constructors in PHP, along with a couple of real-world examples. You saw how to create a constructor and some use cases for constructors in PHP classes.

Check out some of our other posts on object-oriented programming in PHP!

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.