Beginning your journey in Object-Oriented Programming using PHP

Object-Orientated programming is not a new idea! It’s been around and available for a long time in many languages.

With each new version of PHP, new features appear, while existing features are improved. PHP’s object support has been hugley improved since it’s introduction in PHP3 (yes it has had it all this time!). And so with PHP’s object support maturing, the reasons developers might not take an object orientated approach are getting smaller. More recently PHP5′s take on objects is much more powerfull and usable than it ever has been for PHP users – but still not without it’s faults.

A common problem that experienced (and new) PHP developers have when embarking on their object-orientated (OOP) journey is thet they don’t know WHEN to use it properly! As with all things there is a time and place for everything.

For those who do not know about OOP I am not even going to attempt to explain what it is! But fact you have found this article means you probably do, but incase not Wikipedia has good general background info on OOP.

Traditional vs. Object-Oriented

Let’s start by comparing traditional top-down programming with object-oriented programming.

Let’s assume we’re trying to define some variables that describe two houses.

Top-down programming might look like this:

$house1_type = "Apartment";
$house1_address = "123a My Street";

$house2_type = "Mansion";
$house2_address = "123 Millionaires Row";

The OO approach is’nt much different, code for it might look like this:

class House
{
  public $type = "";
  public $address = "";
  public $residents = array();
}

$house1 = new House();
$house1->type = "Apartment";
$house1->address = "123a My Street";

$house2 = new House();
$house2->type = "Mansion";
$house2->address = "123 Millionaires Street";

Looking at this it looks almlost the same and your initial thought will be “That’s more code for the same thing!”.

Since good programmers are a bit lazy (but in a good way!) we want to write less code but make it do more. Which is not always the best approach!

Object-Oriented Programming – Why and When to use it…

At the most basic level the best difference between OO and traditional programming is that it is more organised.

However, that does not always mean better. Think on a messy desk… you probably know where everything is – even if others see a disorganised midden, and would probaly take ages to find something if asked for it!

So, the traditional approach can START OUT clean, the code stays small it’s a great way to create a a quick and efficient program.

However as it evolves, it will more then likley get messy as you add more features. Which in turn means the larger the application becomes, it will become more and more time consuming to document and maintain. Also, as an application growa so does the possibility of multiple people working on it as well as yourself and would you want to suddenly wade through a load of messy code? I think not.

You are probably thinking “Why bother?”, well… it’s makes sense to organise and plan the code at the beginning which may mean writing a little more code initially, but this can/will save you a lot of time later – allowing you to be lazy again!

So, in the reak world, these are the reasons for using an OO (Object-Orientated) approach:

  • Maintenance, makes it easy to add to/enhance as code grows.
  • Makes it easier to work in teams.
  • Documentation is simpler to do.
  • Portable code (for selling, sharing, or reusing code)

Object-Oriented Programming – How to Do It

OK, now we know why we want to do it, and a little bit of when to use it. Lets look at how to do it 🙂

In any OOP programming, life always starts as a “class”. A simple class looks like:

class House
{
}

On it’s own a class does not a lot. This simople defines a class called ‘House’.

To use the House class, simply create an ‘instance’ by using the ‘new’ command:

$yourHouse = new House();

This creates a variable called $yourHouse (an instance of the House class). You can create as many of these as you want:

$yourHouse = new House();
$myHouse = new House();

Class Properties

With no definition or distinct properties $yourHouse and $myHouse are basically the same. Let’s define them by adding some ‘propeeties’. First task – add something to your class:

class House {
	public $mailingAddress = "123 Default Address Street";
	public $numberBedrooms = 2;
}

By doing this we have created two ‘properties’, $mailingAddress and $numberBedrooms.

For now, don’t worry what public means – just add it in front of your class properties. As you might have guessed, we have assigned some ‘default’ values (just as you do for any variable).

However, now when we craete the instances, both have the same mailing adderess and number of bedrooms. While in some cases ‘2’ for bedrooms will cover many ‘default’ houses, the address wont so lets not define one!

class House {
	public $mailingAddress;
	public $numberBedrooms = 2;
}

$mailingAddress is now just a property with no default. So, lets again create our houses:

$yourHouse = new House();
$yourHouse->mailingAddress = "123 Your Street";

$myHouse = new House();
$myHouse->mailingAddress = "444 My Street";

Incase you did’nt guess, assigning a value to a property is simply:

$instance_variable->property_name = value;

And accessing it is similar:

$myHouse = new House();
$myHouse->mailingAddress = "444 My Street";
echo $myHouse->mailingAddress; // Will display "444 My Street"
echo $myHouse->numberBedrooms; // Will display "2"

In simple terms, that’s all you need to know about basic class properties. I will cover that in a future article.

Class Methods

The real guts of a class are “methods”, which are simply functions inside the class:

class House
{

	// Our Class Properties
	public $mailingAddress;
	public $numberBedrooms = 2;
	
	// Our Class Methods
	public function cleanBedrooms()
	{
		for($i = 1; $i <= $this->numberBedrooms; $i++)
		{
			echo "Cleaning bedroom " . $i;
		}
	}
}

That’s more like it! And again we see this “public” keyword, and again, we’re going to ignore it for now.

As you can see the cleanBedrooms() class method is simply a basic basic loop that goes from 1 to the number of bedrooms and echoes out a message that says “Cleaning bedroom 1”, then “Cleaning bedroom 2”, etc

How did the function know how many rooms??? The secret to is the $this keyword. The $this keyword is a reference to the current instance, so if your code was:

$yourHouse = new House();
$yourHouse->numberBedrooms = 10;
$yourHouse->cleanTheHouse();

$myHouse = new House();
$myHouse->numberBedrooms = 5;
$myHouse->cleanTheHouse();

The loop for $yourHouse would run 10 times, and $myHouse 5 times.

In OOP, the $this keyword is one of your most useful tools when writing class methods, as it allows you to reference the properties and
methods of ONLY a specific instance of that class.

Now add a final method that uses an argument and returns a value:

class House {
	// Our Class Properties
	public $mailingAddress;
	public $numberBedrooms = 2;
	
	// Our Class Methods
	public function cleanTheHouse()
	{
		for($i = 1; $i <= $this->numberBedrooms; $i++)
		{
			echo "Cleaning bedroom " . $i;
		}
	}
	
	public function hasMoreThanRooms($numRooms)
	{
		if($this->numberBedrooms > $numRooms)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

$yourHouse = new House();
$yourHouse->numberBedrooms = 10;
if($yourHouse->hasMoreThanRooms(8))
{
        print "Your house has more than 8 rooms? Wow.";
}
else
{
        print "You don't have more than 8 bedrooms? Where am I supposed to sleep?";
}

$myHouse = new House();
$myHouse->numberBedrooms = 5;
if($myHouse->hasMoreThanRooms(4))
{
        print "My house has more than 4 rooms? Wow.";
}
else
{
        print "I don't have more than 4 bedrooms? Where are you supposed to sleep?";
}

Executing this will display:

Your house has more than 8 rooms? Wow.
My house has more than 4 rooms? Wow.

Scope – Public and Private

This is the last important basic aspect to a class. Scope. When we’ve been creating properties/methods with “public” in front of their name, we’re saying they are visible to any code inside or outside of the class.

Take the following example:

class House {

  public $window = "clear";
  private $bathroomMirror = "shiny";

  // Inside the class - code in here can access the values
  // of $window AND $bathroomMirror
  
  public function doSomething()
  {
    echo $this->window; // Will show "clear"
    echo $this->bathroomMirror; // Will show "shiny"
    echo $this->runSecretFormula();  // Will show "Hello world!";
  }

  private function runSecretFormula()
  {
    return "Hello world!";
  }
}

// Outside the class - code here can only access the value of $window.
// Trying to access $bathroomMirror from here would not work.
$myHouse = new House();
echo $myHouse->window; // Will show "clear"
echo $myHouse->bathroomMirror; // OH NO! Will give you a big, fat, fatal error if you try to run the script!
echo $myHouse->runSecretFormula(); // OH NO! Will also give you an error!

It’s common when starting with OOP just to make everything “public”, so why use private at all?

Personally I use it for 2 reasons, 1) hide functionality that does’nt need to be immediatley apparent and 2) for security. It just makes life that little bit tougher, if I have a private property and somone tries to access it they will just get an error.

Obviously a determined hacker will find ways! But it helps protect. But there are ways to protect against it. Compilation to machine language and/or obfustication. Using a combination of these will make life very difficult for them! But all this is beyond the scope of this article!

Also,you can have a “protected” scope, but we’ll leave that for another day!

Hopefully you’ve enjoyed, and you should now have all you need to know to make some meaningfull use of classes/OOP!