Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Use Classes in Programming for Efficiency

Classes can be used to provide shortcuts and helpers throughout programming. For example, you might have a class to define a user. You can then add functions (known as methods) to that user class for common things that users might need to do, like update their passwords.

Without classes, you'd end up having numerous functions laying around in your programs, possibly clashing with each other.

Imagine the scenario (this really happened) where you write a set of user management programs without classes. These programs would include functions like changePassword, addPermission, setEmail, and so on. Now you want to merge that code with someone else's to add the capability to use groups or roles into your program. Their programs are also written without classes, and they have some of the same function names as your programs, like addPermission.

When you attempt to merge them, you'll find no end to the confusion and function name collisions. By the time you get done merging the code, you could've just written it all from scratch again!

On the other hand, if you define your programs using classes, then the addPermission function (method) would never collide with another function because the addPermission method is tied to the user class.

Recall that to create a user in an object oriented manner (called instantiating a user object), you use the New keyword. For example, if your user class was called User (for lack of a less descriptive term), you'd instantiate it like this:

$user = new User;

Then when you call methods, you call them through your own copy of the user object, like this:

$user->addPermission();

Now there can't be a conflict because a group object would be called something different.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.