Page 1 of 1

Class creation fail check... help please!

Posted: Fri Nov 07, 2008 5:54 pm
by Citizen
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?

Re: Class creation fail check... help please!

Posted: Fri Nov 07, 2008 6:15 pm
by requinix
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
}

Re: Class creation fail check... help please!

Posted: Wed Nov 12, 2008 2:53 pm
by Citizen
Thanks! Why is it called statically?

Re: Class creation fail check... help please!

Posted: Wed Nov 12, 2008 3:05 pm
by requinix
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.