HomePHP Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
Enforcing Object Types in PHP: Using the PHP5 instanceof Operator
This is the second installment of the series “Enforcing object types in PHP.” Welcome back. As you’ll surely know, this three-part series goes through the basic concepts of object type enforcement in PHP 4/PHP 5. It explores different approaches for checking types of objects to help you avoid possible code contamination when objects of incorrect type are inputted within PHP classes.
In accordance with the concepts that I discussed in the first part of this series, enforcing object types in PHP can sometimes be a crucial process. When it is avoided, either by lack of knowledge, incorrect programming assumptions, or simple laziness, you certainly may see undesirable effects during the execution of a specific Web application. Particularly when you’re programming with PHP 4, verifying the type of object which you’re working with can be easily achieved by using the “is_a()” function (although there are other methods). It definitely can be used for filtering input objects that need to be passed in as parameters to other PHP classes within the same application.
Nevertheless, PHP 4 does expose some weaknesses related to its Object Model that incidentally can demand writing additional code in order to implement certain features found in mature object-oriented languages. This fact has been well known for a long time by the PHP community. However, with the release of PHP 5, many of these highly desired features were added as part of the improved Object Model. They can help considerably in the development of tighter object-based code, allowing you to work with specific object features with minor hassles.
This is particularly noteworthy in the terrain of object type enforcement, since PHP 5 provides developers with at least two thorough methods for checking the type of objects during the execution of an Web application. These are the “instanceof” operator and the “type hinting” feature, respectively. Coming to the subject of this second tutorial, I’ll introduce the use of the “instanceof” operator in PHP 5, which, as you’ll see soon, can be really handy for determining whether the objects you’re using belong to a particular type.
The end result of this article hopefully will help you to expand your grounding in how to implement object type enforcement in PHP 5, by developing some illustrative, object-oriented examples. Are you interested in learning how to verify the type of your input objects in PHP 5? Right, let’s get started.