...

View Full Version : How to use classes



ninnypants
08-06-2008, 01:10 AM
I've had some experience programing with php and have been working with some open source applications. I have noticed that all of these classes use classes. I have heard of classes before and know that they are used in OOP, but what is the advantage and how would I use a class once I had it built?

Fou-Lu
08-06-2008, 04:09 AM
Purpose of a class can be summed up in one word: encapsulation. This means any data relevant to the actual object in question is all stored within that object. I'll use the classic user as an example. A user is an object with two attributes, a userid and a username. Any user stored in the system is a type of user object with the corresponding userid and username, and these attributes can be accessed within this object:


class PHP5_User
{
private $userID;
private $username;
public function __construct($userID, $username)
{
$this->userID = $userID;
$this->username = $username;
}
public function getUserID()
{
return $this->userID;
}
public function getUsername()
{
return $this->username;
}
}

class PHP4_User
{
var $userID;
var $username;
function PHP4_User($userID, $username)
{
$this->userID = $userID;
$this->username = $username;
}
function getUserID()
{
return $this->userID;
}
function getUsername()
{
return $this->username;
}
}

$user = new User(1, 'Fou-Lu'); // Choose either example for the 'User' class, 'PHP4_User' or 'PHP5_User';
printf("Hello &#37;s!<br />\n", $user->getUsername());

Pros:
- Easier to write and debug (big problems broken into smaller parts)
- Portable and reusable
- Specialized for logical data encapsulation
- Extensions, Abstracts and scope control in PHP5

Cons:
- (A lot) More memory usage
- Often more code than procedural to perform the same task

Objects are great for reusability. If objects are correctly built, you can reuse you're code over and over again to easily create new sites with little or no modification on the logic. Generally I do not use classes and objects for any type of output unless its a template handler. Sometime in the past I shifted to an n-tier style logic which has flowed over into my PHP. This logic fits great with databases - one table generally corresponds to one object.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum