PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Thu Nov 14, 2019 12:47 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 3 posts ] 
Author Message
PostPosted: Sun Aug 08, 2010 4:37 am 
Offline
Forum Commoner

Joined: Wed Jan 20, 2010 2:30 am
Posts: 51
Syntax: [ Download ] [ Hide ]
<?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.


Top
 Profile  
 
PostPosted: Sun Aug 08, 2010 6:03 am 
Offline
Forum Commoner
User avatar

Joined: Mon Apr 07, 2008 11:08 am
Posts: 26
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.


Top
 Profile  
 
PostPosted: Sun Aug 08, 2010 10:15 am 
Offline
Forum Commoner
User avatar

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


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron
Powered by phpBB® Forum Software © phpBB Group