Ok - Say you're doing some MySQL and you have to keep track of a database connection, result resource and all that gunk, well you can encapsulate all of those inside an object and just use things like
$db=&new MySQLThing(); //automatically connected to the DB for you with default settings
$db->query("Use mydb");
$db->query($myquery);
$db->fetch_row();
There's no mukking about with all those variables as they're in the database class. Also with MySQL if you create a new connection with the same details as before, unless you specifically ask it not to it'll return the same resource ID, so if you seemingly open two connections in the same script, then close one the other gets closed as well. I write functions to populate dropdowns or whatever from a db and then close them at the end of the function and still get away with it with my slapdash horror of a mysql class that uses a sort of reference counting thing:
class MySQLThing
{
var $dbh, $res;
var $dbCons; //this will be a simulated static.
function MySQLThing($user="", $pass="",$host="")
{
static $dbCons=array();
$this->dbCons=&$dbCons; //this is how the pretend static happens
$this->connect($host,$user,$pass)
OR $this->death("Couldn't Connect to MySQL Database:");
}
function connect($host="",$user="",$pass="")
{
if($this->dbh) $this->close();
$res=$this->dbh=mysql_connect($host, $user, $pass);
@$this->dbCons["$this->dbh"]++;
/*echo "This Con: $this->dbh<br>"; print_r($this->dbCons); echo "<br>"; //*/
return $res;
}
function close()
{
if ( isset( $this->dbCons["$this->dbh"] ) )
{
$refCount=--$this->dbCons["$this->dbh"];
if( $refCount <= 0)
{// echo "CLOSING REF COUNT ZERO<br>";
return mysql_close($this->dbh);
}
//else echo "NOT REALLY CLOSING REF COUNT: $refCount<br>";
}
else return 0;
}
The commented out bits are just my debugging cack, ignore that. Anyway objects save a hell of a lot of headaches.