I’ve been reading through Effective Java by Joshua Bloch. I also develop in PHP and I wanted to implement the builder pattern outlined in item 2, but PHP doesn’t have inner classes. Is there any way to achieve this pattern in PHP, keeping the constructor for the product private?
Share
Since PHP does not support inner classes, there must be a public method on the product class that creates an instance of it. Consider the following PHP classes:
Note that in the above example the constructor of
NutritionalFactsis public. Due to the constraints of the language, however, having a public constructor is not at all bad. Since one must call the constructor with aNutritionalFactsBuilder, there are only a limited number of ways to instantiateNutritionalFacts. Let’s compare them:To leverage function chaining to its fullest extent, “
NutritionalFactsInstantiation #2″ is the preferred usage.“Update: In PHP 5.4.0, there is now support for the syntax in “NutritionalFactsInstantiation #3″ shows another nuance of PHP syntax; one cannot chain a method on a newly instantiated object.NutritionalFactsInstantiation #3.” I haven’t tested it yet though.Making the Constructor Private
You could make the constructor private, but I wouldn’t recommend it. If the constructor were made private, a public, static factory method would be necessary, as in the following code snippet. Looking at the below code, we might as well make the constructor public instead of introducing indirection just to make the constructor private.