<

Object Oriented Programming (OOP) in PHP: The Class

Published on
14,339 Points
3,439 Views
9 Endorsements
Last Modified:
Awarded
Community Pick
Object Oriented Programming is by far the best way to program. Now, procedural programming does have its place. For example, if you just needed a simple form submission, you wouldn't want to go through all the work in creating a ton of classes for that little job. But if you are:

1) Programming an application that might expand or add new features
2) Programming an application that was written procedurally and is a big mess, or
3) Just wanting to convert to the best programming practices the world has ever known

then Object Oriented Programming (OOP) is for you!

OOP is a concept fairly new to PHP. It was introduced in version 4 as an afterthought, and wasn't well designed. Then in PHP5, OOP really started taking a hold of things, providing a good amount of room to use OOP. Now, as we look toward the future, PHP6 should have fairly complete support for OOP. But at this moment, we will embrace OOP with version 5.

To jump-start your life into OOP, we'll just start with the basics. The heart and soul of OOP is a Class. Think of a class as a robot. It has a blueprint on how its designed and built. That's what we create, the blueprint that PHP interprets. We start by letting PHP know that we want to create the blueprints for a class like so:
 <?php
	class SimpleRobot {}
?>

Open in new window


This simply means that we want to create a SimpleRobot. This SimpleRobot can't do anything, though! Let's rewrite our blueprint to allow him to walk:
<?php
	class SimpleRobot {
		function walk(){}
	}
?>

Open in new window


Now, I'm guessing that you know how to create a function, right? Well that's all a class is! Its a container for variables and functions! Let's give our robot some knowledge by adding some variables!
<?php
	class SimpleRobot {
		var $power = "Electricity";
		var $location = array('x'=>'0', 'y'=>'0');

		function walk($direction){}
	}
?>

Open in new window


Simple right? But how do we actually use the robot? Well, we have to let PHP know to create a new SimpleRobot:
<?php
	$robot = new SimpleRobot();
?>

Open in new window


Wait a minute! That looks like a function! But what's with that new keyword there? Well, its not a function, trust me. The new keyword lets the PHP parser know that we want to create a New copy of something, being whatever follows the keyword. The parenthesis after the class name allows you to pass arguments when the class is created. We'll get to that, but lets focus on actually using the class first.
Now that we have created an Object, we can start playing around with it! A copy of the class is now stored in the $robot variable. To access different parts of the class, we use the dash and greater than keys: ->. Think of it as an arrow pointing to PHP what we wanting to use out of the variable. So, if we wanted to move the robot, we would do it like so:
<?php
	$robot = new SimpleRobot();
	$robot->walk("left");
?>

Open in new window


So we are telling PHP to look for a function (the walk function) and call it, passing it the "left" argument. What if we want the value of a variable stored in the class? Easy. Use the same symbol as before:
<?php
	$robot = new SimpleRobot();
	echo $robot->power;
?>

Open in new window


This will output, "Electricity". But wait! We didn't put the $ sign before the word "power"! That's right! PHP knows that you have to either be calling for a function or a variable. Since we didn't put the parenthesis after the name, it knew we must want a variable. Okay, that's all well and nice, but what about working with variables and functions Inside the class? Well, it's just about the same way, but slightly different. Since we want to refer to the object we are currently using, we need a way to refer to that specific object. Well, how about referring to $this object!
<?php
	class SimpleRobot {
		var $power = "Electricity";
		var $location = array('x'=>0, 'y'=>0);

		function walk($direction) {
			switch($direction){
				case "left":
					$this->location['x'] -= 1;
					break;
				case "right":
					$this->location['x'] += 1;
					break;
				case "forward":
					$this->location['y'] += 1;
					break;
				case "backward":
					$this->location['y'] -= 1;
					break;
			}
		}
	}
?>

Open in new window


So now we see that by specifying $this we tell PHP to work with the current object that we called the function from. Let's see how this works with multiple robots to get the idea:
<?php
	$robot1 = new SimpleRobot();
	$robot2 = new SimpleRobot();

	$robot1->walk("forward");
	$robot2->walk("backward");

	echo $robot1->location['y']; //outputs 1
	echo $robot2->location['y']; //outputs -1
?>

Open in new window


Now do you understand how classes work? Each variable holds an object specified by the class you stated. Each variable holds data for that object that is specific to THAT object, and THAT object only. This way you could create a whole bunch of objects each with their own data:
<?php
	for($i=1;$i>10000;$i++){
		$robot$i = new SimpleRobot();
		$robot$i->location['x'] = rand(1, 999);
		$robot$i->location['y'] = rand(1, 999);
	}
?>

Open in new window


OK, one last thing. I told you that you can pass arguments to the class when you construct it right? Well how on earth do we do this then?! PHP has some magic functions that you can override and build yourself. One of them, as we can guess, is the __construct() function (note: that is two underscores before construct):
<?php
	class SimpleRobot {
		var $power = "Electricity";
		var $location = array();

		function __construct($x = 0, $y = 0){
			$this->location['x'] = $x;
			$this->location['y'] = $y;
		}

		function walk($direction) {
			switch($direction){
				case "left":
					$this->location['x'] -= 1;
					break;
				case "right":
					$this->location['x'] += 1;
					break;
				case "forward":
					$this->location['y'] += 1;
					break;
				case "backward":
					$this->location['y'] -= 1;
					break;
			}
		}
	}
?>

Open in new window


This function is one of the most useful functions you will ever use. So now you know the basics of OOP in PHP! Now, start toward the path of ultimate programming and enjoy!
9
Comment
Author:LordZardeck
1 Comment
 
LVL 20

Expert Comment

by:Mark Brady
After reading your article, I have a better understanding about some of the things that can be achieved with OOP. Looking at your "robot" example it helped me understand how gaming programmers work, with objects and classes right? So they give commands to their object to move around the screen and the object moves! Pretty cool tutorial, thanks!
0

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Join & Write a Comment

Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.
Other articles by this author

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month