-2

In a code i've come across a class which had this function at the start:

private function __construct() {

    }

Why would there be an empty function at the top? Is there any purpose to this? Or does this depend on the rest of the code? If it does could anyone give me an example in which this would be useful.

Kevin
  • 81
  • 8

2 Answers2

2

The only thing this achieves is to stop people instantiating the class with the new keyword (notice the constructor is private).

Cameron Ball
  • 3,960
  • 5
  • 22
  • 30
1

Using a private constructor allows you to create a class that can't be instantiated. For example, when it contains only static methods. It's common, for example, with classes that implement the factory pattern.

Alex Howansky
  • 44,270
  • 7
  • 68
  • 92