Published on : 01.05.2010 Category : PHP Classes Viewed : 57 times.
Some consider classes one of the hardest components of PHP to figure out, but the reality is that classes are extremely straightforward and easy to use. The trouble comes from the fact that not all programmers have worked with Object-Oriented Programming (OOP) before. Classes are little more than a container for variables and functions affecting those variables, but they can be very useful for building small components - almost miniture programs. The difference is that you dont need to shell out to them or anything, and they can be plugged into most scripts with ease - Just a require or include statement at the top. A class describes an 'object'. An object is a collection of smaller objects, just like in a class. Say for instance, we want to describe a simple door lock. A lock class might contain:
Code:
variable $Bolt variable $Position function TurnKey( $Direction, $Distance ) function CheckLock( )
TurnKey would accept a direction value that would in turn determine if the bolt should be locked or unlocked. Once the key is turned far enough in either direction ($Distance) the Bolt will either set or clear. The $Bolt variable shows the current state of the door lock, and $Position is used to track how far the key has been turned in any direction. Now, obviously this could all be done with regular variables and functions, and if you only need to use one lock in the code, it would probably work just fine. But what if you want more than one lock? One if you wanted more details about the lock, or even something else? Maybe you want a door in the code, too - And the lock would just be a subset of the door. Maybe you have a whole house. You might have more than one door, or you might not. But each door certainly needs a lock. You can see how complex object-related problems can get. By using classes, you can define an object once, and then include it in several scripts also. You'll be assured that your object will funciton the same in all of the scripts! Its good practice to write your classes in a seperate file usually, that way you only have to change it in one location. Make full use of PHP's include and require functions, they have many uses. In the next section, I will walk you through creating a simple class.
|