Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Running a function on creation of a class 2

Status
Not open for further replies.

Geee

Programmer
Apr 23, 2001
253
GB
Hi,

I am currently using a db class to handle my database functions, but I want to connect to the DB every time an instance of that class is created. I am currently doing this:

Code:
	class db { // class for handling db access

		var	$dbc = array('host' => 'localhost', 'user' => 'root', 'pass' => 'vivodigital007', 'db'=>'dmm');
		// db config details

		var $debug = 0;
		// set debugging to OFF by default

		function connect($name='dmm') { // connects to the database
		// connects to the mysql database

			$dbconn = mysql_connect($this->dbc['host'], $this->dbc['user'], $this->dbc['pass'])
				or die('Could not connect: ' . mysql_error());
			// connect to the msql db or die and display error

			mysql_select_db($this->dbc['db']) or die('Could not select database: '.$name);
			// select the mysql database or die and display error
		}

And then using the class as follows:

Code:
require_once('db.inc.php');
$db = new db;
$db->connect();

What I would like to do is to connect automatically when the php creates an instance of the class. Is this possible please?

-Geeeeeeeeeeeeeeeeeeeeeeee-
 
I'm rusty on PHP OO but I think you need a constructor in the form of

Code:
function sameNameAsTheClass(){
    //this is called when the class is instantiated
}

Don't quote me on that though, I may have got something wrong somewhere.

--
Tek-Tips Forums is Member Supported. Click Here to donate

<honk>*:O)</honk>

Tyres: Mine's a pint of the black stuff.
Mike: You can't drink a pint of Bovril.


 
sure

add this method to the class. it will be called as an implicit constructor when you create the class

Code:
public function db($name = 'dmm'){
  $this->connect($name);
}
 
Cheers both been googling but couldn't find what I wanted.

-Geeeeeeeeeeeeeeeeeeeeeeee-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top