PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
Citizen
Forum Contributor
Posts: 300 Joined: Wed Jul 20, 2005 10:23 am
Post
by Citizen » Fri Nov 07, 2008 5:54 pm
I run this class:
Code: Select all
class Clan {
public $info = array();
function Clan($id) {
global $App;
$sql = "SELECT * FROM `clan` WHERE `clan_id` = '$id' LIMIT 1";
$result = $App->query($sql);
$num = mysql_num_rows($result);
if($num == 1){
$row = mysql_fetch_array($result);
$this->info = $row;
}
else{
$this = NULL; // returns an error
unset($this); // doesnt work
}
}
}
Which I want to run like this so that it returns false if $num does not == 1:
Code: Select all
if($aClan = new Clan($cid)){
// stuff goes here
}
Any ideas?
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Fri Nov 07, 2008 6:15 pm
You can't do it that way. Constructors do one thing and one thing only, and you're asking of it what can't be done.
Try something like this instead:
Code: Select all
class Clan {
public $info = array();
public static function get($id) {
global $App;
$sql = "SELECT * FROM `clan` WHERE `clan_id` = '$id' LIMIT 1";
$result = $App->query($sql);
$num = mysql_num_rows($result);
if($num == 1){
$row = mysql_fetch_array($result);
$clan = new Clan;
$clan->info = $row;
return $clan;
}
else{
return false;
}
}
}
if($aClan = Clan::get($cid)){
// stuff goes here
}
Citizen
Forum Contributor
Posts: 300 Joined: Wed Jul 20, 2005 10:23 am
Post
by Citizen » Wed Nov 12, 2008 2:53 pm
Thanks! Why is it called statically?
requinix
Spammer :|
Posts: 6617 Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA
Post
by requinix » Wed Nov 12, 2008 3:05 pm
Citizen wrote: Thanks! Why is it called statically?
It allows you to get a false if there isn't a clan with that clan_id. With a constructor you have to populate an object; with a static function you can be flexible with what happens.