HomePHP Defining an Abstract Class with Restrictive Constructors in PHP 5
Defining an Abstract Class with Restrictive Constructors in PHP 5
In this second part of a four-part series, I rebuild the example application developed in the previous tutorial. As you'll recall, it used a protected constructor to prevent the instantiation of the base array iterator class. In this case, a better result will be achieved by declaring the iterator abstract; still, the example demonstrates a simple utilization of a restrictive constructor in a concrete situation.
Unquestionably, the introduction of a more robust object model in PHP 5 has provided developers with additional features that allow them to build efficient and thorough object-oriented applications without the need to appeal to the ugly programming hacks used frequently in the bad old days of PHP 4.
As you may know, among those features there’s one in particular, called member visibility, which permits you to explicitly declare methods and properties of classes as public, protected and private respectively. Being used to PHP 5 by now, specifying the level of accessibility (or restriction) that certain members of a class will have in a specific context should be a familiar process that isn't especially noteworthy.
However, there’s a case where member visibility can be particularly appealing. This happens when you're working with restrictive constructors, or in other words, when using constructors that have been declared either protected or private.
Indeed, there are a number of situations where restrictive constructors can be of great help, even though the topic seems to be rather irrelevant at first glance. But it is not, trust me. The correct implementation of common design patterns, or even the construction of purely static classes, often require working with protected and private constructors. This implies that the subject deserves a close look.
In keeping with this requirement, in the introductory part of this series I developed a basic array iterator class that involved working with a protected constructor, which was used to prevent the direct instantiation of the iterator in question.
This approach is frankly pretty pointless, as this issue can be addressed simply by declaring the aforementioned class abstract. Even so, this example came in handy for offering a friendly introduction to using protected constructors in a concrete case. However, in the next few lines I’m going to rebuild the example developed in the preceding tutorial, this time using an abstract iterator class.
Now, let’s leave the preliminaries behind us and continue learning more about using restrictive constructors in PHP 5. Let’s jump in!