Page 1 of 1
can't understand this class
Posted: Sun Aug 08, 2010 4:37 am
by everydayrun
Code: Select all
<?php
/**
* Database actions (DB access, validation, etc.)
*
*/
class DB_Connect {
protected $db;
/**
* Checks for a DB object or creates one if one isn't found
*
* @param object $dbo A database object
*/
protected function __construct($dbo=NULL)
{
if ( is_object($db) )
{
$this->db = $db;
}
else
{
// Constants are defined in /sys/config/db-cred.inc.php
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
try
{
$this->db = new PDO($dsn, DB_USER, DB_PASS);
}
catch ( Exception $e )
{
// If the DB connection fails, output the error
die ( $e->getMessage() );
}
}
}
}
?>
the above is a class to DB
the above is a class for DB access, validation, etc. why he declared a constructor function and what it will do?i have just started with the PHP programming language, so I am not having much idea about it and the try.....catch block.any tips would be appreciated.
Re: can't understand this class
Posted: Sun Aug 08, 2010 6:03 am
by novito
Hi,
I believe that what the meaning of this is like saying "If they give me a Data Base object" I will assign it to the class, if not I will create a new one. I would risk to say that this might be useful if you already have opened a DB connection, but correct me if I'm wrong.
Hope this helps.
Re: can't understand this class
Posted: Sun Aug 08, 2010 10:15 am
by MindOverBody
Duno if you know, but constructor is method that will be triggered upon making instance of a class. Yap, novito sadid well, constructor checks if given parameter is object, if yes, it set it as connector object, else makes the new one.
Inside Try code block, is code where xou can expect some error, and on some occurance of error you can throw exception which will Catch block actualy catch on fly, and do its code block. Usuali it is to show error message or so.