Classes and objects in PHP
|
Author: Mattias (mattias@999tutorials.com) Categories: General www, PHP |
|
|
|
The tutorial: Digg this, Post to del.icio.us, 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... 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 objectsObjects 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 classI 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 = ""; function getFirstname()
This class is not that useful, but it is how the basics for classes work. 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! Digg this, Post to del.icio.us, |
