spacer
spacer
activepages
spacer

Week 7: PHP Intro to Objects and Classes

This week's notes build upon this page here.

PHP's Object Oriented capabilities may not be complete, but some benefits of convenience and code re-use from using Objects and Classes are available in the PHP language. If you are already dabbling in PHP, but haven't yet checked out Classes, have a look at this simple (yet useful) example of an Error Message Class.

Beginners Guide to Object-Oriented Terminology

Sometimes when people are introduced to OOP via a technical presentation, the terminology serves as a barrier - partly because people explaining it usually try to stress what is different about OOP, rather than saying how it is tied to natural concepts we deal with every day. In many ways, OOP came about as a way of packaging existing good ideas and practices, but then evolved into common programming and scripting language constructs that consistently implement a OOP perspective. We expect to gain a certain clarity when organizing and coding our projects using the OOP way.

There are four terms that you should attempt to feel comfortable with in order to discuss OOP concepts with others: Class, Object, Property and Method.

A Class is a blueprint for creating an Object. It tells you what variables (a.k.a. Properties) the Object can have, and what functions (a.k.a. Methods) can be used to manipulate the Object's Properties.

Each of us has a blueprint of ourselves in our DNA that encodes all the information necessary to create us from scratch. We are an object, made up of many sub-objects that anatomists discuss at varying details. The Human Genome Project attempts to generate a basic Class of information that could better explain how human DNA directs the generation of a human being. In OOP terms, The class would be the consistent attributes and abilities that a human contains that could be documented for us to use when evaluating any human object. Our attributes in OOP terms are properties (which I have been calling members). Examples include our two arms, our two legs, our heart, etc. (a human has lots of properties). Our Methods in OOP terms are our abilities. Examples include breathing, digesting, circulating oxygen, etc. (a human has a lot of abilities as well). We try and take an object-oriented approach to human understanding so that we can have specialties that allow for diagnosing and correcting issues that arise in our health. We go to a pediatrist if we have issues with our feet. We go to an optomologist if we have problems with our eyes, etc.

When writing a computer-based system to do useful work, we can break down the overall responsibilities for managing and performing activities to different specialties in the system. Many systems designers have found the OOP perspective to provide a useful division of control for managing the complexities of a large system. The Web is a large system and so we find that OOP use in popular Web programming languages and scripting languages can help us work on small pieces of our Web components and yet have them work with existing Web components when we are ready for them to do so. In this class, we look at some classes (Form, Document, and Database being the three obvious ones). With a good OOP vocabulary in place, we can also begin to document how they work together.

My first good introduction to OOP terminology used a biological cell as an example. The components of the cell such as the membrane, nucleus, cytoplasm, etc. were some key member objects of the cell. Energy generation, waste management, chemical communication, and osmosis were some of the key methods associated with a cell class. In this case, the author uses a man-made example:

A Real-World Example

Consider an old-fashioned radio, with an on/off switch, and a tuning dial.

The Class is the circuit diagram and assembly instructions that enables the worker to build the radio, and also the User Manual that describes how to operate and fix the radio.

Each and every radio built using that circuit diagram and assembly instructions becomes an Object.

The methods associated with a radio are something like:

Build Radio ( )
Turn Radio On ( )
Turn Radio Off ( )
Tune Radio ( )

The Properties might be:

serial_number - to uniquely identify the radio.
status - whether the radio is currently on or off.
current frequency - to which the radio is tuned.

Every Object has the same methods available. Every Object has values for the same Properties - but the specific values for the radio may be different. Indeed in our radio example, the serial number should always be different.

We can create the Radio as a class using the available features of the PHP language:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Radio Class Example</title>
</head>

<body>
<?php
class Radio {

   var $serialno = '0';
   var $on = false;
   var $station=93.3;

   function __construct($sno, $stn){
      echo "creating a radio object<br>";
      $this->serialno = $sno;
      $this->station = $stn;
   }
}
$mine=new Radio("34N5632", 103.7);
echo $mine->station;
?>
</body>
</html>

But, the benefit of using a class structure is we can modularize our code to only use classes when we want to include the objects they create in our solutions. To use the Radio class, we can include the radio.php file and then create our radio object in a separate file (and comment out the two use lines from our radio.php file. Let's create a file named use_radio.php with the following code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Radio Class Example</title>
</head>

<body>
<?php
include("radio.php");
$mine=new Radio("34N5632", 103.7);
echo $mine->station."<br/>";
?>
</body>
</html>

By doing so, we have extracted the use of the object apart from the declaration of the object. We can provide the opportunity to use our class without having to burden the user with the details of how it is implemented. The hiding aspect of detail is another benefit of programming with an OOP style.

Go ahead and add a function to your class declaration in your radio.php file:

function changeStation($new_station) {
    $this->station = $new_station;
}

You can change the station now when you use the radio class in the use_radio.php file (add the following two lines to change the station and print it out again:

$mine->changeStation(104.5);
echo $mine->station."<br/>";


Now let's add another member to the radio class definition:

var $url="http://kfog.tunegenie.com/#listenlive";

Now you can actually play the station from its online web page by using an HTML IFRAME element (add the following lines to deliver the station to your audience):

echo '<iframe src="'.$mine->url.'" /></iframe>';

Note there are quite a few streaming music stations. Use the streema.com service to get a URL or this directory here.

You have now built an object with available members and method.

One key task for gaining a useful OOP perspective is the task of organizing data and actions that you want your code to process into classes. The more natural the class structure, the less you will have to refer back to the documentation to use your code over and over. The more you think you understand the concept that the class represents, the more the code should resonate with you when you go to use it. You've created HTML forms before and the ability to do so is relatively simple because the HTML language limits the options available to you. Once you fully internalize all that an HTML form can do, you begin to be able to use the Form class in complex processing systems.

Adding a request form

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Radio Class Example</title>
</head>
<body>
<form action="createradio.php" method="get">
Type: <input type="text" name="type" value="internet" />
Station: <input type="text" name="station" value="http://tunein.com/radio/HPR4-Bluegrass-Gospel-s117404/" />
<input type="submit" value="OK" />
</form>
</body>
</html>

The updated radio class used in radio production:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Radio Class Example</title>
</head>

<body>
<?php
class Radio {

   var $serialno = '0';
   var $on = false;
   var $station=93.3;
   var $url="http://tunein.com/radio/181FM-Front-Porch-%28Bluegrass%29-s55024/";

   function __construct($sno, $stn){
      echo "creating a radio object<br>";
      $this->serialno = $sno;
      $this->url = $stn;
   }
  
   function changeStation($new_station) {
      $this->url = $new_station;
   }
}
?>
</body>
</html>

The radio service:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Radio Use Example</title>
<style>
#station {
    width:500px;
}
</style>
</head>

<body>
<?php
include("classes/Radio.php");
if($_GET['type']=='internet') {
    $radio=new Radio("34N5632", $_GET['station']);
}
echo "<h2>MY RADIO</h2><br/>";
echo '<iframe src="'.$radio->url.'" /></iframe>';
echo '<form action="createradio.php" method="get" />';
echo '<input type="hidden" name="type" value="internet" />';
echo '<input type="hidden" name="serialno" value="'.'34N5632'.'" />';
echo 'New Station Request: <input id="station" type="text" name="station" />';
echo '</form>';
?>
</body>
</html>
NOTE: Once we've learned AJAX, we'd separate the radio change functionality with the whole radio delivery process.

If you would like to practice the PHP Object-oriented syntax, Code Academy has a couple of good lessons to help you practice:

1. PHP Objects
2. PHP Object-Oriented

So why do programmers like Classes?

Keeping variables as Object Properties saves you from having to use global variables. Good for security. It also avoids accidentally using the same variable across two different sets of functions.

All Object Properties are available to all functions (a.k.a. Methods) within the Class. So you are not having to specify lots of variables as global within each function, or pass them in as parameters.

Class definitions make me keep everything to do with the Class in one place. With collections of functions it is easier to write code that is harder to maintain.

Just thinking in terms of Classes, Properties and Methods seems to help get my mind around the problem.

If you are using Sessions, by registering the Object with the Session, all the Object's Properties are automatically serialized, stored in the session and then unserialized for you on the next page. Handy.