HomePHP Enforcing Object Types in PHP: Filtering Input Objects in PHP 4
Enforcing Object Types in PHP: Filtering Input Objects in PHP 4
When you are writing an object-based web application in PHP, you want to prevent your classes from being convoluted with input objects of the incorrect type. These input objects can cause the application to throw a fatal error. In this article, you will learn how to enforce object types in PHP 4.
During the development cycle of an object-based Web application, it’s a pretty common task to work with some PHP classes that accept other objects as part of their input parameters, whether they’re assigned as class properties for further use, or processed right at the moment of being passed in.
At first glance, this might seem like a hassle-free situation, and certainly there wouldn’t be a real need to worry about it. Nevertheless, reality can sometimes be quite different, a fact that can quickly break down a PHP application. In order to illustrate this, let me put you in the right context: you’re using a MySQL data processing class, which takes a query result object as its input argument for processing at a later time. As long as the correct type of object is passed into the processing class, everything is going to work just fine, but what if the class is fed with the wrong type of object?
I’m sure you can imagine the result: sooner or later, the application will fail in processing the object and throw a fatal error, causing the abrupt termination of program execution -- not to mention a bunch of additional error messages that might be displayed, eventually, by the PHP parser. Moreover, if the application is being tested on a local server, the situation won’t go beyond the developer’s own frustration -- but if it’s being run in a production environment, consequences might be much worse.
So, what’s the lesson of this story? Right, you guessed it. Obviously, the problem could be easily fixed by forcing the class in question to check the type of objects being passed in, so the class itself and the rest of the application code can’t be contaminated by objects of incorrect types. My conclusion about all this is that checking and enforcing object types in PHP is indeed an important topic that deserves an in-depth look, so in this series I’ll explore different approaches for verifying object types, either when programming with PHP 4 or PHP 5.
By the end of this series, hopefully you’ll have a clear idea of how to force object types inside of your PHP application, in this way avoiding further problems related to the so-called code contamination. Let’s get started.