Forum Moderators: coopster

Message Too Old, No Replies

Not sure whether I should be using a static method or not (PHP5)

         

formasfunction

9:17 pm on Apr 2, 2008 (gmt 0)

10+ Year Member



I'm torn about the best way to implement the following functionality. I have a Group class (as in, a club a users can join) and in it I have the following two methods, among others:


static public function join($id, $level=1){
global $database, $account;
if(self::isMember($id, $account->getId())) throw new Exception("You're already a member of that group");
$database->query("INSERT INTO ".TBL_MEMBERS." SET group_id = ".$id.", user_id = ".$account->getId().", level = ".$level);
}
//
// returns true if the given user id is a member of the group
static public function isMember($g_id, $u_id){
global $database;
$result = $database->query("SELECT * FROM ".TBL_MEMBERS." WHERE group_id = ".$g_id." AND user_id = ".$u_id);
return (mysql_numrows($result) > 0);
}

The join() method is static in order to allow the request to be processed without instantiating an object and I'm using the isMember() method to test whether or not the user is already a member before adding them to the DB. The problem I have is that I want to use isMember() for various other parts of the site where I will be instantiating a Group object and my code would be much cleaner if the isMember() method looked more like this:


// returns true if the given user id is a member of the group
public function isMember($u_id){
global $database;
$result = $database->query("SELECT * FROM ".TBL_MEMBERS." WHERE group_id = ".$this->getId()." AND user_id = ".$u_id);
return (mysql_numrows($result) > 0);
}
//the call would look something like: $g->isMember($u_id)

But I can't have it both ways and I'm not very knowledgeable of what constitutes "good form" so any help would be greatly appreciated.

cameraman

10:13 pm on Apr 2, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Is it important to not instantiate an object - in other words, couldn't you instantiate a temp object for joining purposes? That way neither function would need to be static.

If not, then you could have both a static and non-static version of isMember (LOL is what I'd do if the above isn't an option, although I'm admittedly self-taught OOP and adhering to conventions for convention's sake has never been much of a priority).

formasfunction

10:09 pm on Apr 6, 2008 (gmt 0)

10+ Year Member



Thanks for giving me a second opinion; I ended up going with your advice. I just wanted to make sure there wasn't a slicker way to take care of it before I conceded.