Home > Tutorials > PHP Tutorials > The Basics of PHP Classes and Objects

The Basics of PHP Classes and Objects

As you learned in previous tutorials functions provide a way for you to divide your program’s tasks into separate, smaller tasks. Classes and objects are somewhat similar in helping you to organize your program. They are used to create collections of related variables and functions, which can be used to more accurately represent real-life situations. So you might have a content management application you are working on which will consist of a wide array of classes intended to deal with the various parts of you CMS. For example you may have a class for adding/updating pages, displaying templates, and displaying pages. Each one of these classes will hold within it a set of functions and variables intended to make everything associated with that class function. So the displaying pages class may contain functions for getting the page content from the database, getting the appropriate page template, and displaying the page.

Let’s take a look at some example syntax to get a better grasp at how a PHP class is setup. We’ll re-create the classic Hello World application, adding in some extra functionality to allow a user to choose the text they want to display and also select how it should be formatted.

class HelloWorld
//variables of the class
 var $headerBold = "<h1>Bold</h1>";
 var $headerItalic = "<h1>Italic</h1>";
//Function of class
public function write($userMsg, $format)
	if ($format == 1) {
		$codeStart = "<b>";
		$codeEnd = "</b>";
		$msg = $this->headerBold;
		$msg .= $codeStart.$userMsg.$codeEnd;
	} else {
		$codeStart = "<i>";
		$codeEnd = "</i>";
		$msg = $this->headerItalic;
		$msg .= $codeStart.$userMsg.$codeEnd;
	echo $msg;
$objClass = new HelloWorld();
$objClass->write("Hey Guys!", 1); // 1 for Bold, 2 for Italic

Let’s start at the beginning. To create our HelloWorld class we use the class keyword, followed by the class name, followed by an opening brace and a closing brace. All of our specifics and logistics of the class go between these braces.

Next we declare some of the properties, or variables, we will be using within the various functions of our class. As we have covered before you can utilize variable scope here to define whether or not a variable should be public or private. Take note that when declaring class variables, they must be declared with the var keyword. Variables that are not declared as class variables are not declared with the var keyword.

Next up we have class functions which are just like regular functions, except they are defined inside a class definition. Class functions are known as methods, and they can be used to either retrieve data or manipulate data. We will be referring to class functions as ‘functions’ or ‘methods’ interchangeably throughout this lesson.

In our above example we have the write() method which takes in two parameters – the text to be written and the format option for that text. Then we use a simple if/else statement to figure out what exactly should be displayed.

We’ve also used a new keyword here, $this$this is a special keyword used when creating classes. The purpose of it is to refer to the current class. It’s interchangeable with the class name, so the following two snippets are both essentially the same:

$msg = $this->headerBold;
$msg = $write->headerBold;

Lastly we need to actually make use of the class we have written. To do this we must create an object which will reference the class. The process of creating an object is called instantiation. You can create an object by creating a variable which stores the object, and using the new keyword and the name of the class to instantiate from. In our above example this is:

$objClass = new HelloWorld();

Now we need to go ahead and make use of the function within our class, and to do this we simply reference our function by name:

$objClass->write("Hey Guys!", 1); // 1 for Bold, 2 for Italic

Subsequently if we wanted to reference a class variable we have defined, or echo out a class variable we would use much the same format as referencing a class function:

echo $objClass1->headerBold;

This gives us a good overall grasp of the basic structure of a class and how to use it. So let’s take a look at a slightly more complicated example – this time incorporating within itself multiple functions and making proper use of variable scope to utilize a variable across multiple functions within the class. We’re going to write a script that will randomly generate a new Pokemon everytime it’s loaded. We will have the ability to select the Pokemon nickname, and to set a range of minimum and maximum values for the Pokemon’s HP and Attack points.

class pokemon
	var $nickName;

function chooseName() //Randomly chooses the Pokemon
    $name = Array("Charmander", "Pikachu", "Seal", "Bulbasaur");
    $pName = $name[rand(0, count($name) - 1)];
	global $key;
	$key = array_search($pName, $name); 
	return $pName;
function displayNickname() //Displays the nickname passed to the function
	return $this->nickName;	
function chooseType() // Selects the Pokemon type based on the key set in the chooseName() function above
	global $key;
	$types = Array("Fire", "Electric", "Water", "Leaf");
	$t = $types[$key];
	return $t;
function getRandomNumber($min, $max) // Selects a random number based on a minimum and maximum range
    $values = range($min, $max);
	$k = array_rand($values);
	$a = $values[$k];
	return $a;
$objPokemon = new pokemon;
$objPokemon->nickName = 'Firey';
echo "You Pulled A <b>" . $objPokemon->chooseName() . "</b><br/>";
echo "Nickname: <b>" . $objPokemon->displayNickname() . "</b><br/>";
echo "Type: <b>" . $objPokemon->chooseType(2) . "</b><br/>";
echo "HP: <b>" . $objPokemon->getRandomNumber(80, 180) . "</b><br/>";
echo "Attack: <b>" . $objPokemon->getRandomNumber(40, 95) . "</b><br/>";

While our original Hello World application above does make use of Classes and Objects – it’s quiet simple in nature. In-fact you could say it doesn’t really need to be written in such a fashion at-all and can be a standalone function. The Pokemon generator above however utilizes several different functions, and several different variables – giving us something with a similar structure to one you’ll find in other applications.

A few key things should be mentioned here. First off take notice of the global scope that is given to the $key variable in the first function – thus allowing me to utilize it across the remainder of the functions in our Pokemon generator.

Only the first function does any random picking, in our case it randomly picks one name from our array of Pokemon names. This name is then returned by the function. The $key variable is then set to hold the numerical key telling us what position in our array the randomly chosen name is. This way the Pokemon type can be appropriately selected. Now yes this could have all been accomplished with an associative array – however this was a fun example to get everyone used to working with Class & Object structures in PHP.

I do urge you to fork the code however and play around on your own.

The displayNickname() function simply returns the Pokemon’s nickname we set:

$objPokemon->nickName = 'Firey';

Again these functions can be further cleaned up by bringing the HTML formatting inside each function, and changing the returns to echo statements. However for the purpose of this tutorial I wanted to get as much different functionality in it as made sense.

About Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Check Also

5 Must Have WordPress Optimization Plugins For A Fast Loading Website

Having a fast loading website is essential these days. First off, users are impatient. If ...

Like every other website, this site uses cookies to analyze our traffic. Cookies may also be utilized by our advertisers and partners. By using this website you agree to the use of said cookies. More Information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings, continuing to navigate past this message, or you click "Accept" below then you are consenting to the use of cookies on the Rapid Purple website.