There are many ways to create programming code. One of the easiest but most powerful is to start using object oriented way to think and work. I will give you the basic how you create a class, and why.

Have you written a lot of “db connect” in your projects? How many places do you have the username and password for your database?

What happens when you want to change the password for you database? Or if you change host and has to change server name or database login?

Sure this can be taken cared of in config files, but an even better way to do things is to start using classes, objects and Object Oriented programming.

I will not give you the school explanation, neither you or I have the time for that…
The simple explanation is that, if you for example have a member, a company and a role in a project you create… then you have three classes, one for member one for company and finally one for project.

What can ONE member have? Probably firstname, lastname, age, street address etc etc. then you need to be able to define these and also retreive these when you need it.

This is what objects/classes are for :-)

Very simple,you have an object for every member in your system. They are defined by a class. So you have a class that say that your members have firstname, lastname and age. But the object handles ONE single member.

Work with objects

Objects have “set” and “get” methods. Pretty simple, set is for setting an attribute and get is for getting it. So if we have a member object we can get hist firstname and lastname etc, but we can also change it for that member if we like to.

Create a class

I want to give you a very simple example on a class. This class is for handling a member, and the member have a firstname and lastname.

class cMember

{

var $firstname = “”;
var $lastname = “”;

function cMember()
{
}

function getFirstname()
{
return $this->firstname;
}

function getLastname()
{
return $this->lastname;
}

function setFirstname($firstname)
{
$this->firstname = $firstname;
}

function setLastname($lastname)
{
$this->lastname = $lastname;
}
}

This class is not that useful, but it is how the basics for classes work.
You have attributes, which is firstname, lastname.
You have functions that return the attributes and you have functions that set new values for the attributes.

The reason for having functions to do everything is that the rest of your project don’t need to know how that information is handled internaly, only this class needs to. So IF you change the whole member thing, you can basicly change it in this class and it works everywhere else. Probably it will not be that beautiful, but you will be soooo much closer to this than you have before. :-)

I can write more about object orientation if you are interested, just let me know by email!

Similar Posts: