HomePHP Page 4 - Inheritance and Polymorphism in PHP: Building a Form Generator - Part II
Coming up: more subclasses - PHP
In part two of this three-part series, we refresh our memory of Inheritance and subclasses from part one, and take our first stab at implementing a form generator.
If you think that the above class definitions are not enough for building our form generator, you're right. There are still more form elements to be defined. So, it's time to continue defining more form subclasses. The next one to be defined is a <textarea> element, listed below:
class textAreaObject extends formObject {
var $value;
var $wrap;
function textAreaObject($label,$name,$style,$value,$wrap='virtual'){
The above listed class for building a <textarea> element accepts two additional parameters: $value and $wrap, in order to use them for proper HTML generation. In this case, we've given a default value of "virtual" for the $wrap parameter.
Now let's look at the form button elements. Its class definition is the following:
class buttonObject extends formObject {
var $value;
function buttonObject($label,$name,$style,$value){
Finally, we're going to show our last two classes: form image elements and submit buttons. First, here's the code for form image elements, often used for submitting forms without using the venerable submit button:
class imageObject extends formObject {
var $value;
var $src;
var $alt;
function imageObject ($label,$name,$style,$value,$src,$alt){
I must give a short disclaimer: notice that in all of the subclasses that accept a $value parameter, we've opted not to consider as a valid argument any numeric value. While this validation process could be leaving out some potentially valid parameters, we've chosen to do this based on a data type checking rather than performing validation on data length. For particular cases, just implement the validation process you believe best suits your needs.
Now we have fully defined each subclass derived from the form base class for creating the form generator. Since subclasses nicely expose the "generateHTML()" method, it is easy to figure out a technique to put all of the subclasses to work and build a complete HTML form. So, let's try creating a regular form, using the above defined classes.