Constructors | Object Oriented Programming in PHP

In my previous post on Object-Oriented Programming, we learned about Access Modifiers. Let’s take the discussion forward to some advanced concepts. In this article, we will discuss Constructors.

If you are new to Object Oriented Programming, please read my beginner post on it first.

Class Constructors

A constructor is a special method in a Class that initialises the object of that type. It usually has the same name as that of the class and can be used to set values of the object’s members.

Constructors are not explicitly called and are invoked itself as soon as the object is created. As a result, a constructor is only called once in it’s lifetime.

Basic PHP Constructor

In older PHP, we used to define a constructor method in the following way:

<?php
	class BaseClass {

		public function BaseClass() {
			echo 'Base Class Constructor Called';
		}

	}

	$a = new BaseClass();
?>
Output:
Base Class Constructor Called

On creating the BaseClass object, the constructor is invoked automatically. However, PHP 5 introduced a new functionality to define a constructor. We will be using the new functionality from now on.

The old style constructors are deprecated in PHP 7 and they will be removed in future versions. Therefore, you should always use the new functionality to define a constructor.

Syntax:

__construct($arguments);

For instance, consider the code snippet to demonstrate the functioning of constructor.

<?php
	class BaseClass {

		public function __construct() {
			echo 'New Functionality Base Class Constructor Called';
		}

	}

	$a = new BaseClass();
?>
Output:
Base Class Constructor Called

Constructor Design Recommendations

We recommend the following while designing a constructor:

  • Any operation like opening a connection to a database should not be written in the constructor.
  • Since a constructor cannot return a value, we should throw an exception if anything goes wrong.
  • Always call the Parent Class Constructor in case of Class Inheritance. We will discuss it in detail in a later post.
  • Constructors should be declared as public. If the constructor is private then we cannot instantiate an object of that class. This will be demonstrated in an example.
  • If you don’t want to perform any operation in a constructor, then it is not mandatory to define it.

Examples

Let’s discuss a few examples to demonstrate the working of constructors.

Example 1: Initialising Default Values

<?php

	class Pagination {

		private $limit;
		private $offset;

		public function __construct() {
			$this->limit = 10;
			$this->offset = 0;
		}

	}

	$paginationObject = new Pagination();
	print_r($paginationObject);
	/*
	Pagination Object
	(
	    [limit:Pagination:private] => 10
	    [offset:Pagination:private] => 0
	)
	*/

?>

In the example above, we declare a simple Pagination Class. The class has two private members, limit and offset. When we create a new object of the class, it invokes the constructor of the class. The constructor sets the default values of limit and offset member variables.

Example 2: Parameterized Constructor

We can also set user-defined values to members using a constructor. For instance, consider the example below:

<?php

	class Pagination {

		private $limit;
		private $offset;
		private $totalPages;
		private $currentPage;

		public function __construct($totalRecords, $currentPage) {
			$this->limit = 10;
			$this->offset = 0;
			$this->totalPages = (int) ($totalRecords / $this->limit) + 1;
			$this->currentPage = $currentPage;
		}

	}

	$paginationObject = new Pagination(55, 1);
	print_r($paginationObject);
	/*
	Pagination Object
	(
	    [limit:Pagination:private] => 10
	    [offset:Pagination:private] => 0
	)
	*/

?>

We modify the earlier example a bit by introducing 2 new member variables. We pass total records and current page as parameters to the constructor. The constructor assigns the values of the variables accordingly.

Example 3: Private Constructor

If you define a private constructor, then you can’t instantiate a class object.

<?php
	error_reporting(E_ALL);ini_set('display_errors',1);
	class classTest {

		private function __construct() {
			//
		}

	}
	$classTest = new classTest();
        //Fatal error: Uncaught Error: Call to private 
          classTest::__construct() from invalid context
?>

However, you can get an instance of such a class by calling the constructor from within the class. This will come in handy in designing Singleton Classes. I will discuss Singleton Design pattern in a later post.

<?php
	class ClassTest {

		public static function getInstance() {
			return new classTest();
		}

		private function __construct() {
			echo 'Private Constructor Called';
		}

	}
	$classTest = ClassTest::getInstance();
        //Private Constructor Called
?>

Additionally, you may read about the static keyword in this article.

Conclusion

In conclusion, we covered Constructors in this article. You may go through other PHP articles on Concatly. Also, there is a lot more to learn on the Official Documentation on Constructors.

I hope you found this article helpful. Kindly leave your valuable comments provide any suggestions.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *