phptutorials.cjb.net - Free PHP Tutorials and Advice
 

PHP Classes Tutorial 1 - Database Abstraction and Classes Tutorial - Page 3 of 7

A Bit of Class

Right then, we have discussed a bit of theory and object basics, now we are going to define our class. We will start out simply and build on from there.

To connect to a database server three vital bits of information are required, the host, the username and the password. These details will be passed to the class when it is created. To create a class we use the new operator, this calls a method known as, appropriately enough, the constructor.
The constructor is a special method that has the same name as the class it is defined in, our class is called phpDBConnector so our constructor will also be called phpDBConnector. Like so:


<?php
	class phpDBConnector
	{
		var $connect_id;

		// constructor accepts host, username and password details
		function phpDBConnector( $host, $username, $password )
		{
			// constructor code
		}

		// rest of code
	}

	// Create object, $DB from class phpDBConnector, with 
	// host=localhost, username=username password=password.
	$DB = new phpDBConnector( 'localhost', 'username', 'password' );
?>

We will pass the host, username and password to the constructor, which will then attempt to create the connection to the database server.

When methods within the class wish to access the classes internal variables it must use the pseudo-variable $this which can be read as 'my own' or 'current object'.  Thus our constructor code becomes:


<?php
	class phpDBConnector
	{
		var $connect_id; // needed to keep the database connection open

		function phpDBConnector( $host, $username, $password )
		{
			$this->connect_id = @mysql_connect( $host, $username, $password );
		}

		// rest of code
	}

	// Create object, $DB from class phpDBConnector, with 
	// host=localhost, username=username password=password.
	$DB = new phpDBConnector( 'localhost', 'username', 'password' );
?>

OK so we can connect to a database, what about doing something with it? Continue to next page...