I use classes more and more often because:
- you don't get so confused in complex projects
- you can dereference classes from each other, varying them without fuss
- you can store complex objects in arrays, loop through them in order to do the same with all of them
- you don't have to work with functions that take lots of parameters which you don't overlook
now I will describe an example, perhaps it's interesting to someone 😉 sorry, it got quite long ...
I have created a set of classes which represent HTML inputs.
class Input has two dereferenced classes:
HiddenInput and VisibleInput.
and VisibleInput has
TextInput, Checkable (-> Checkbox, RadioButton)
and so on.
this far it seems more complicated than just writing a html form.
now every VisibleInput has a Label (for example: "Enter your name:").
you can create a textinput like this:
$t = new Textinput();
$t->setName('username');
$t->setLabel('Enter your name:');
once you have all the inputs you want to be included in your form, create a Form object an add the inputs to it.
$f = new Form();
$f->setAction('post.php');
$f->addItem($t);
...
you can add multiple inputs in a loop.
now, if you want to display the Form as an HTML table, do the following:
$f->setStyle('table');
or, if you want each input line by line:
$f->setStyle('normal');
if you want the labels on the right of each item, you can adjust it easily:
$f->setLabelAlign('right');
finally, produce the whole HTML code:
echo $f->getHTML();
for me, the best idea I had when designing this, is a SQLSelectbox. it's basically a normal selectbox (from which it is dereferenced) but you can set an sql statement as an attribute:
$s = new SQLSelectbox()
$s->setName('id_customer');
$s->setSQL("select id,name from customer");
echo $s->getHTML();
voilà - that's really fun to use.
if I had used functions, I would have had to copy the selectbox() function, rename and modify the copy.
a bug in the original function? -> correct both functions. (bah!)
with object orientation, I just have to debug the superclass (Selectbox).
the point is, using this programming style reduces the complexity of your scripts drastically (not of your project library, but of the scripts which make use of it). imagine you designing a site that has 50 form pages in it.
now, the code needed for producing a medium-complex form is free of plain HTML, thus far better maintainable. you can turn switches by calling a method such as $f->setLabelAlign('bottom');
I have tried this with functions before, and I got lost in my 15 parameters for some inputs and functions calling sub-functions and so on.
but class hierarchies have to be designed well, so if you already hate designing databases, this will be no fun for you.