1

Is there such a situation where __construct() would be declared anything but public?

If so, why?

3 Answers3

1

A common example for making the constructor private or protected is implementing the singleton pattern. See this answer for a PHP example.

Community
  • 1
  • 1
molnarm
  • 9,856
  • 2
  • 42
  • 60
  • What would such a design pattern be used for? Forgive me for the "noob" question. –  Mar 09 '13 at 20:37
  • 3
    @DustinL. see http://stackoverflow.com/questions/4595964/who-needs-singletons/4596323#4596323 – Gordon Mar 09 '13 at 20:39
  • In other languages, they are used for classes that should have only once instance: resource managers, caches, loggers, etc. – molnarm Mar 09 '13 at 20:40
  • 1
    @Gordon Thanks! Love the flowchart as well! :) –  Mar 09 '13 at 20:43
1

I also use private constructors when using the builder pattern inside the class, and also when adding static factory methods for a class.

Both can help you to avoid creating too many constructors, and also help you to create constructors with meaningful names. For example instead of:

new Robot(2, 4, 255, 0, 0)

You can create with builder:

RobotBuilder.withNumberOfArms(2).withColor(255,0,0).withNumberOfEyes(2).build()

As the builder is inside the class, only it can call its private constructor.

For static factory methods, you can see that these:

public static Robot createFourArmedRobot();
public static Robot createBlindRobot();

are much more meaningful for an other developer than two constructors with custom parameters. (More relating to OOP than php)

abbath
  • 2,444
  • 4
  • 28
  • 40
0

Usually we do __construct() as private for singleton pattern that is related to design patterns to know more about it visit this page - http://en.wikipedia.org/wiki/Singleton_pattern