0

Constructors in PHP 5+

Background

This article demonstrates how constructors work in PHP. It will also touch on destructors just briefly. If you’re a Java programmer who has somehow become bored with anything Java and wanted to explore PHP, the first thing you need to realize is OOP in PHP is slightly different. Take for instance, constructors.

The constructors in PHP work differently to that of Java’s.

Software Requirements

  • Windows 7 Professional SP1
  • PHP 5.5.9 / Zend Engine v2.5.0
  • NetBeans IDE 8.0.1

Constructor Definition

In PHP 5+, constructors are defined using the keyword __construct as a method name. This is the recommended way of definining constructors.

Also note that you cannot overload any functions in PHP. That includes methods like constructors.

Inheriting and Overriding Constructors

In a parent-child classes, when a subclass has its own constructor and is instantiated, the parent constructor is never invoked. There are two ways to have the parent constructor executed:

1. Explicitly call the parent contructor from the subclass’ constructor

2. Do not override the constructor in the subclass

This effectively executes the parent constructor.

Destructor

If you are familiar with Object.finalize() in Java or methods annotated with @PreDestroy, the equivalent of that in PHP is the destructor method. Destructors are defined using the __destruct keyword.

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert