phptutorials.cjb.net - Free PHP Tutorials and Advice
 

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

Object Basics

A Class is a design for a variable, an object is an implementation of that design. Classes are a collection of variables and functions (or methods) acting on those variables. A Classes variables are private, and so should not be accessed directly but via its defined methods. In this way a class is treated as a 'black box'. In technical speak: 'Classes are types, that is, they are templates or blueprints for actual variables. These variables are known as objects.'

An example class definition might look like this:


<?php
	class phpDBConnector
	{
		var $host;
		var $username; ...

		// Constructor
		function phpDBConnector( $host, $username, etc... )
		{
			$this->host = $host;
			$this->username = $username;
			// rest of code
		}

		function setUserName( $uname )
		{
			$this->username = $uname;
		}

		function getHost()
		{
			return $this->host;
		}
	}
?>

You have to create an object of the desired class with the new operator. Like so:


<?php
	$dbConnection = new phpDBConnector( 'localhost', 'username' ... );
?>

To access the classes private variables ( $host and $username in this case ) we use the classes methods:


<?php
	$dbConnection->setUserName( 'mattp' );
	echo 'Current host is ' . $dbConnection->getHost();
?>

You can find out more about Classes and Objects at the PHP Website. (opens new window)