can't understand this class

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
everydayrun
Forum Commoner
Posts: 51
Joined: Wed Jan 20, 2010 1:30 am

can't understand this class

Post 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.
User avatar
novito
Forum Commoner
Posts: 26
Joined: Mon Apr 07, 2008 11:08 am

Re: can't understand this class

Post 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.
User avatar
MindOverBody
Forum Commoner
Posts: 96
Joined: Fri Aug 06, 2010 9:01 pm
Location: Osijek, Croatia

Re: can't understand this class

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