Page 1 of 1

SOLVED! HELP: php class destroying

Posted: Mon Sep 27, 2010 5:31 am
by itimeheke
Hi all. I need to destroy(destruct) class inside itself.
Lets say i have construct method like so:

Code: Select all

public function __construct($host = NULL, $user = NULL, $pass = NULL, $debug = false) {
	        if (!$host OR !$user) {
			// THIS IS THE PART I CAN'T FIGURE OUT
                }
		$this->debug = (bool) $debug;
		return $this->connect($host, $user, $pass);
	}
So, if variables $host or $user are not given, then i need to destroy this class. And also set the variable assigned to class as NULL.
Example:

Code: Select all

$test = new mysql();
Cause variables $host and $user aren't given, variable $test must be NULL, not an object.

Is that possible?

Regards, Kristian.

Re: HELP: php class destroying

Posted: Mon Sep 27, 2010 5:54 am
by greyhoundcode
How about throwing an exception from within the constructor (if it doesn't like the arguments it's been passed)?

Re: HELP: php class destroying

Posted: Mon Sep 27, 2010 6:26 am
by itimeheke
Okay, i did not explain well. For this last example, i need to set variable $test to NULL or FALSE from class 'mysql' constructor without (error)message displayed and script execution halted.

Re: HELP: php class destroying

Posted: Mon Sep 27, 2010 8:19 am
by requinix
You explained yourself just fine.

What you want to do cannot be done. The closest thing for a constructor is to throw an exception. Just like greyhoundcode said.
The alternative is to not use the constructor and try a factory pattern instead.

Re: HELP: php class destroying

Posted: Mon Sep 27, 2010 8:52 am
by DigitalMind
Maybe my example will be suitable for you...

Code: Select all

class DBConn {
    private static $db = NULL;
    static function conn($host = NULL, $user = NULL, $pass = NULL, $name = NULL, $port = 3306, $debug = false) {
        if (self::$db !== NULL) {
            return self::$db;
        }
        self::$db = new mysqli($host, $user, $pass, $name, $port);
        return self::$db;
    }
    private function  __construct() {
    }
    private function  __clone() {
    }
}

$dbconn1 = DBConn::conn('localhost', 'testuser', 'testpass', 'testdb');
$dbconn2 = DBConn::conn();
$dbconn3 = DBConn::conn();
$dbconn1, $dbconn2 and $dbconn point to the same mysql connection. It's also possible to use something like $stmt = DBConn::conn()->prepare('select name from test where id = ?').

Re: HELP: php class destroying

Posted: Mon Sep 27, 2010 9:17 am
by itimeheke
Okay, thanks. Now i know:)

digitalmind:
Yeah, my connecting method is exactly the same:) It returns mysql resource, when it exists.

Thanks for helping ya all!