I haven't made a "camp" yet in OOP where I am comfortable.
As a procedural guy, I'm sure that you used functions a few times. Like, for instance, a "makeSafe()" function to clean user input, or a "dbconnect()" function for connect to multiple databases.
Objects are like taking a group of functions that perform similar tasks, and letting them know they're related. For instance, let's say that you are building a script to edit a config file. You'd want one function to addconfig(), one to editconfig and one to deleteconfig() at the very least. However, all of these functions have a few things in common. First, they are all dealing with the config file. Second, they are all going to be dealing with a similar sort of input structure, (i.e. $config_name, $config_value).
You could do things the procedural way and just write three complete functions, but with an OOP method, we can let these functions know they perform similar tasks by putting them in a class. This allows us to pull out common threads between them, such as the location of the config file, and make them variables which are shared only among these similar functions.
<?php
class config {
// variables in a class are things which the functions
// have in common
public $config_file;
function config($config_file) {
// open the config file...
}
// functions in a class are specific tasks which can be done
// to the whole group of things the class addresses
function addconfig() {
....
}
function editconfig() {
....
}
function deleteconfig() {
....
}
function closeconfig() {
}
}
?>
This is helpful in reducing code base size and keeping things organized, but it has functional advantages too. For instance, now you could state the base information once, and perform multiple tasks on the config file:
<?php
include('./config.class');
$config = new config("/usr/local/someprogram/cfg/config.cfg");
// assuming that the $config_names and $config_values variables exist
// and contain valid data for use in the class
// You can add the configs that are supposed to be added...
$config->addconfig($config_add_names, $config_add_values);
// ...edit the configs that need editting...
$config->editconfig($config_edit_names, $config_edit_values);
// ...and delete the configs which are no longer needed.
$config->editconfig($config_del_names, $config_del_values);
$config->closeconfig();
?>
And this is just a quick example. The ways you can optimize and reduce coding AND processing time by letting functions which perform similar tasks know they are similar are many and varied.
I decided to start downloading a few classes from well know sources, and try to pick them apart as a way to learn.
😃 Same way I did it. You must be a masochist though... it's REALLY difficult. Almost no one comments their code well, and none of them comment it with any of the basics of OOP.