Jump to content
MakeWebGames

[OOP] How to define a class. PART 1


Floydian

Recommended Posts

Note that much of this article will only work with PHP 5. If you're still using PHP 4, I'd recommend that you upgrade and learn OOP in PHP 5 rather than learn the old ways of doing things that won't help you in the job market.

There's a ton of information that could be included here, but my goal is to help the "uninitiated" become comfortable with OOP.

OOP is "Object Oriented Programming".

Click http://criminalexistence.com/ceforums/index.php?topic=22880.0 to see what OOP is and how it differs from Procedural Programming (what most of us PHP noobs use)

Here is the basic syntax for creating a class:

 

<?php
class MyClassName {

}
?>

 

That is just the basic container. It's kinda like defining a function. class replaces function. Note that you do not use () after the class name. In keeping with OOP coding conventions (this is fairly standard across most OOP languages) we use "CamelCase" caps. This means that the first letter of each word is upper case, the rest is lower case, and there are no underscores. This helps seperate classes from functions and objects from variables.

For our class to be useful, we need to add properties and methods. Properties are simply variables. Methods are basically functions.

Let's look at an example of a simple MySQL database class. Try not to get bogged down in understanding what the code here does. I'm far more interested in introducing the patterns that you will see. Trust me, if you're new to OOP, you need to learn the patterns this type of coding follows before any of it will make sense to you. Remember, none of this is linear, it's all over the place, in a good way though ;)

 

<?php
class MyDatabase {

// Define the class properties
private $Host = 'localhost';
private $UserName = 'mememe';
private $Password = '1234abcd';
private $SelectedDatabase = 'my_game';
private $Connection;
private $QueryError;

       // This method will attempt to connect to the database and select a default schema (database)
function Connect() {

               // Attempt to connect to the database.
	$this->Connection = mysql_connect($this->Host, $this->UserName, $this->Password);

               // If the connection attempt failed, we'll detect that here.
	if(!$this->Connection) {

                       // Set an error message and return false so that we know this method failed to do what we wanted it to do.
		$this->QueryError = mysql_error();
		return false;
	}

               // Attempt to select a database. We put this in an if so that we can also detect if this was succesfull
               // at the same time we selected a database
	if(!mysql_select_db($this->SelectedDatabase)) {

                       // If we couldn't select a database, set an error message and return false so we know the method failed to
                       // accomplish it's task
		$this->QueryError = mysql_error($this->Connection);
		return false;
	} else {

                       // If we reached this point, we know we have an active database connection and a default schema selected.
		return true;
	}
}

       // This method's only purpose is to return to us the error message stored in the private property: QueryError.
function GetError() {
	return $this->QueryError;
}

}

?>

 

You've seen how to make the class container in the first example. Now we've pushed things considerably farther. After creating the container, we have declared some private properties. There are three basic options for properties. They can be public, protected, and private. Each of these has specialized uses that goes beyond the scope of this article. But here are the basics.

Properties

A public property is one that can be accessed from outside of the class. It can also be changed from outside of the class.

A protected property is one that can only be accessed from within the class and can only be changed from inside the class.

A private property is one that can only be accessed from within the class and can only be changed from inside the class.

The difference between protected and private is that private properties are not inherited. Huh, what's inheritance? Well, let's leave that alone for now lol. At this point, I think it would be too confusing to inject a discussion of inheritance into the mix.

Private and protected properties seperate the internal operation of your class from outside code far more than public properties. The general rule of thumb is that properties should not be accessed from outside of a class. For instance, you shouldn't ever have a need to access the MyDatabase::Connection property. It should only ever be used internally by the class.

What is MyDatabase::Connection you ask?

We'll talk briefly about the "scope resolution operator". :: is the scope resolution operater. :: is used to reference what class a property belongs to. MyDatabase::Connection is used as a way to reference a class name and a property name. I'll get back to the scope resolution a bit later.

Methods

Now we get to the first method. Methods are defined using the function key word. In fact, they operate much like functions do. Variables in your methods have a scope that is seperate from the global scope. If you aren't familiar with variable scope, may I suggest that you are biting off a bit more than you should be at this point. You really need to have a decent understanding of what variable scope is or class will be confusing. And it's confusing enough as it is without needing to add in more confusion.

Methods are normally named with the CamelCase convention and without underscores, as are properties and class names. Methods can accept parameters to be passed to them, i.e., function blahblah($param1, $param2.....) {}.

$this->

What is that $this you're seeing all over the place in the class definition?

I'm hoping you asked that question as it means you have seen a pattern there. And this pattern is that $this gets used a lot in classes. It's extremely important to learn what $this does. So here it is:

$this refers to your class! Uh, say what?

I know it's confusing. Stay with me here.

Let's visualize our class as an array, shall we? One note, this isn't a syntactically correct array. It's demonstrative of a class though and should help to put into our heads a visual image of the organization of a class.

 

<?php
$MyDatabase = array(
"Host" => 'localhost',
"UserName" => 'mememe',
"Password" => '1234abcd',
"SelectedDatabase" => 'my_game',
"Connection" => null,
"QueryError" => null,
"Connect" => function {
	$this->Connection = mysql_connect($this->Host, $this->UserName, $this->Password);
	if(!$this->Connection) {
		$this->QueryError = mysql_error();
		return false;
	}
	if(!mysql_select_db($this->SelectedDatabase)) {
		$this->QueryError = mysql_error($this->Connection);
		return false;
	} else {
		return true;
	}
},
"GetError" => {
	return $this->QueryError;
}
)
?>

 

I want you to see how each property name and each method name is similar to a key in an array. In fact you can put an object into a foreach loop and access each public property! Methods, protected properties and private properties can't be accessed in this way.

Within the class definition, $this has access to each one of those! $this->SelectedDatabase will hold the value of 'my_game'.

$this->GetError(); will get the error message stored in the MyDatabase::QueryError property and return it. It's basically calling the GetError method! Using $this, you can access any part of a class from inside the class definition.

$this->Connection = mysql_connect($this->Host, $this->UserName, $this->Password);

On that line of code, we get the values stored in three of the properties and use them to create a connection to the database. Then our connection is stored in the MyDatabase::Connection property.

**Random Thoughts**

Instead of talking more about the scope resolution operator, I think it's better that I leave that for later. Classes have an entirely different structure than the code most of us are used to. I really want to emphasize that before you worry too much about what this database class does, I really want you to get used to the patterns that arise in classes.

Specifically: a class definition starts with a list of properties, and then has methods. Methods make a lot of use of the $this variable.

Keep those key points in mind, and classes will start to become a bit clearer.

The last point I want to drill home is that I had to do a lot of consulting with the PHP manual to write all of these articles on OOP. I consider myself to still be a noob to OOP. And I get things wrong with it a lot. I've strived to make the information here as accurate as I can. And I've fact checked much of it, and have tested some of the code as well. Specifically, I've tested the database class and it does indeed connect to the database like it should. I'll leave you with an example of the database class that has some code after it that actually makes use of the class. All it will do is make a connection and then print out a response that tells you if you were connected successfully or not. ;)

 

 

 

<?php
class MyDatabase {

// Define the class properties
private $Host = 'localhost';
private $UserName = 'mememe';
private $Password = '1234abcd';
private $SelectedDatabase = 'my_game';
private $Connection;
private $QueryError;

function Connect() {
	$this->Connection = mysql_connect($this->Host, $this->UserName, $this->Password);
	if(!$this->Connection) {
		$this->QueryError = mysql_error();
		return false;
	}
	if(!mysql_select_db($this->SelectedDatabase)) {
		$this->QueryError = mysql_error($this->Connection);
		return false;
	} else {
		return true;
	}
}

function GetError() {
	return $this->QueryError;
}

}

$db = new MyDatabase();

if (!$db->Connect()) {
echo $db->GetError();
} else {
echo "Successfully connected to the database.";
}
?>
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...