What exactly is a restrictive constructor, and why would you want to use one? If you're a PHP programmer who uses such design patterns as Singleton and Factory, this series of articles on restrictive constructors will give you another tool to use in your applications.
As you'll probably know, with the release of PHP 5 quite some time ago, the language was provided with the ability to specify the visibility of properties and methods in classes, something that had already been implemented in more mature programming languages such as Java and C++.
In a pretty straightforward fashion, PHP developers can establish three different levels of restriction to several class data members, through the use of the "public," "protected" and "private" keywords respectively. It's even possible to appeal to the "final" keyword to make a whole class or method closed to further modifications.
Naturally, at this point member visibility brings nothing new to the table, especially for seasoned programmers with a lot of experience in developing object-oriented applications. However, there's a particular case when this feature can be a bit more interesting than usual. It occurs when using restrictive constructors. But, what are they, actually?
Well, as its name clearly suggests, a restrictive constructor is nothing but a regular constructor method whose level of visibility has been declared protected or private. It's as simple as that. Yet, this rather pragmatic definition also brings with it an intriguing question: why should a constructor be restricted to being accessed only from its originating class or even from a subclass?
True to form, there are a number of specific situations where assigning a stronger level of restriction to a constructor than "public" is indispensable, not to say mandatory. For instance, the implementation of certain creation design patterns, such a Singleton and Factory, quite often requires coding protected and private constructors to more strictly control class instantiation, or when building classes that are intended to be used out of the object context.
Given the variety of cases where restrictive constructors can be truly helpful, in the following lines I'm going to code for you some easy-to-follow examples aimed at demonstrating the use of protected and private constructors in PHP 5.
Ready to take the first step of this hopefully educational journey? Then, let's get started!