Classes

Talk about anything in here.
Post Reply
User avatar
FrederickGeek8
Posts: 148
Joined: Wed Nov 30, 2011 10:31 pm

Classes

Post by FrederickGeek8 »

What is the point of classes? Honestly I just find them to be a hassle to use/program... Why use classes when you could use easier-to-program functions?
User avatar
Helx
Posts: 350
Joined: Thu May 17, 2012 6:45 am
Location: Auckland, New Zealand

Re: Classes

Post by Helx »

'Cause #YOLO. :D

I think they just look more professional, maybe a bit easier to manage.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Classes

Post by jacek »

One advantage is the way you can store data in the instance of an object. For example the forum system I'm working on has a post class and a topic class. The topic class has a method to gets all of the posts on page X, this returns an array of post objects. The post class has methods to access the information like get_user() which returns an instance of the user class for the user that made that post. The user object has more methods like send_message() and ban() that act on that specific user.

The point I'm trying to make is that you can represent multiple entities with one class/bit of code. The methods that they define can act on that specific object as well so there is no need to pass IDs or names around all of the time.

[syntax=php]$topic = new topic($_GET['tid']);

if (!topic->is_valid()){
// sad face !
}

foreach ($topic->fetch_posts() as $post){
echo $post->get_title(), "\n";
}[/syntax]
or written in the classic style

[syntax=php]if (!topic_is_valid($_GET['tid'])){
// sad face !
}

foreach (topic_fetch_posts($_GET['tid']) as $post){
echo $post['title'], "\n";
}[/syntax]
not much more complicated but certainly harder to document since there is now a random array key we have to remember.

Basically it comes down to organisation.
Image
User avatar
Temor
Posts: 1186
Joined: Thu May 05, 2011 8:04 pm

Re: Classes

Post by Temor »

I myself use classes because I want to learn how to use classes properly. Versatility is power... or something.
Post Reply