Class creation fail check... help please!

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

Post Reply
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

Class creation fail check... help please!

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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
}
Citizen
Forum Contributor
Posts: 300
Joined: Wed Jul 20, 2005 10:23 am

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

Post by Citizen »

Thanks! Why is it called statically?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
Post Reply