user1125551
user1125551

Reputation:

In what scenario would constructors be private or protected?

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

If so, why?

Upvotes: 1

Views: 64

Answers (3)

abbath
abbath

Reputation: 2482

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)

Upvotes: 1

Sri Tirupathi Raju
Sri Tirupathi Raju

Reputation: 819

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

Upvotes: 0

molnarm
molnarm

Reputation: 10031

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

Upvotes: 1

Related Questions