Richland College Multimedia Learning Center

Digital Media Programming with PHP and MySQL

PHP Objects

Introduction

PHP supports Object-Oriented Programming (OOP). You can make PHP pages without using OOP, but objects can help you build simpler, more understandable code. In this handout you will learn how to make your own PHP objects. Then, after you understand how to make your own objects, we will talk about why you should use OOP in your PHP pages.


Objects Overview

Objects are things that can help you organize your PHP code and pages. These things called objects contain information and do actions with that information. To be a bit more specific:

Objects have properties and methods.

A properly designed object will incorporate some important OOP features called encapsulation, inheritance, and polymorphism. (You don't need to remember these terms in order to use objects, but it wouldn't hurt for you to be at least familiar with these features of objects.)


Creating an Object

There are two ways in which you can create an object in PHP:

  1. Using the new keyword along with a normal class name
  2. Using the new keyword along with the built-in (anonymous) stdClass name

We will look at the first way, using a normal class name, in this section and the following sections. I will briefly cover anonymous objects toward the end of this handout.

The Basic Airplane page has a very simple object in it, created with a normal class definition. This class, and the object that is created with it, represents an airplane. With a lot of embellishment and modification, you could use an object like this to load, fuel, and fly a fleet of airplanes.

This chart of the processing sequence shown in the code below may help in your understanding of the various PHP statements. This chart is intended to show what occurs in the PHP server's memory and on the HTML page's display as the page is being generated by the PHP statements.

The code for the Basic Airplane page is below. This is page basicAirplane.php:

Note: In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private.

However, var is no longer required.

If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Basic Airplane</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
</head>
<body>
<?php
// BASIC OOP DEMO

//define the airplane class

class Airplane
{
  var $model;
}  // end Airplane class

//make an instance of the airplane

$thePlane = new Airplane();


//assign a value to the model property
$thePlane->model = "Boeing 737";

//display the value of the model property
print "The plane being used for this flight is a ";
print $thePlane->model;

?>
</body>
</html>

Please note these points about the above code:


Adding Methods to a Class

Objects get interesting when they have behaviors as well as data (properties) in them. You add behaviors with methods. An object's methods allow you to do things to, and with, the object's properties.

The Airplane with Methods page has some methods in it.

This chart of the processing sequence shown in the code below may help in your understanding of the various PHP statements. This chart is intended to show what occurs in the PHP server's memory and on the HTML page's display as the page is being generated by the PHP statements.

The airplane class "include" page is airplaneClass.php and it is shown below:

<?php
//define the Airplane class

class Airplane
{

  var $model;

  function __construct($handle = "Piper Cub")
  {
    $this->model = $handle;
  } // end constructor

  function setModel($newModel)
  {
    $this->model = $newModel;
  } // end setModel

  function getModel()
  {
    return $this->model;
  } // end getModel

}  // end Airplane class
?>

The code for the Airplane with Methods page is below. This is page airplaneMethods.php:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Airplane Object</title>
  <link rel="stylesheet" href="myStyles.css">
</head>
<body>
  <div id="mainDiv">
<?php
  if (!isset($_POST['formSubmitted']))
  {
?>
    <form method="post" action="airplaneMethods.php">
      <input type="hidden" name="formSubmitted" value="1">
      Select an airplane:
      <select name="airplaneModel">
        <option value="McDonnell Douglas DC-10">McDonnell Douglas DC-10</option>
        <option value="FA-18 Hornet">FA-18 Hornet</option>
        <option value="F-16 Falcon">F-16 Falcon</option>
        <option value="F-35 Lightning">F-35 Lightning</option>
        <option value="Beechcraft Bonanza G36">Beechcraft Bonanza G36</option>
      </select>
      <br><br>
      <input type="submit" value="Upgrade the Fleet">
    </form>
<?php
  }
  else
  {
    require "airplaneClass.php";
    
    //make an instance of the Airplane
    $thePlane = new Airplane();

    //print original model
    print "Original model: " . $thePlane->getModel() . "<br>\n";

    print "Upgrading the fleet...<br>\n";
    $thePlane->setModel($_POST['airplaneModel']);
    print "Upgraded fleet: " . $thePlane->getModel() . "<br>\n";
    
    print "<br><a href='airplaneMethods.php'>Back to Form</a>";
  }
?>
  </div>
</body>
</html>

Please note these points about the above code:


[OPTIONAL] Default Getters and Setters

You may create default "Get" and "Set" methods for your class. This is an option and is not required.

There is more information than you need in the "Overloading" page at the php.net site. You can view the "Overloading" reference page here.

The __set() method (note the two underscores at the beginning of the name) is run when writing data to inaccessible properties. (An inaccessible property is one which is not "visible" to the class's user.)

The __get() method (note the two underscores at the beginning of the name) is used for reading data from inaccessible properties. (An inaccessible property is one which is not "visible" to the class's user.)

If you try to set or get the value of one of the properties in your class directly, meaning that you use this kind of syntax:

  $obj->a = 1;
  echo $obj->a;

the PHP processor will use the __set() and __get() methods and will not allow you to directly set or get the property's value.

Here is a sample of a class definition which has these default methods in it. This is page PropertyTestClass.php:

<?php
class PropertyTest
{
    //The class will store any "set" data here:
    private $data = array();

    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    public function __get($name)
    {
        if (array_key_exists($name, $this->data))
        {
            return $this->data[$name];
        }
    }
}
?>

And this sample class can be used like in this page, which is page PropertyTest.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>PHP Property Test</title>
</head>

<body>
<pre>
<?php
include "PropertyTestClass.php";

$obj = new PropertyTest();

echo "Create a property a and give it a value of 1...\n\n";
$obj->a = 1;
echo "Property a is " . $obj->a . "\n\n";

echo "Create a property aardvark and give it a value of 'hungry'...\n\n";
$obj->aardvark = 'hungry';
echo "Property aardvark is " . $obj->aardvark . "\n\n";
?>
</pre>
</body>
</html>

You can see this page running here.


Inheritance

Inheritance, you may recall, means that one object can be built from another object, and that the new object contains all of the methods and properties that the original object has. You can add new features (properties and methods) to the new object, but it still contains the features of the original object.

Let's use our Airplane class to make an aircraft maintenance log, using inheritance to expand the class.

First, let's put the Airplane class definition into its own file. This is file airplane.php:

<?php
//define the Airplane class
class Airplane
{

  var $model;

  function __construct($handle = "Piper Cub")
  {
    $this->setModel($handle);
  } // end constructor

  function setModel($newModel)
  {
    $this->model = $newModel;
  } // end setModel

  function getModel()
  {
    return $this->model;
  } // end getModel

} // end Airplane class

?>

Please note these points about this version of our Airplane class:

Now here is a PHP page that uses the Airplane class definition file, and that also adds some new features to the basic Airplane class. This is file InheritAirplane.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Airplane Deployment Tracker</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
</head>
<body>
<?php

// Incorporating Inheritance

//Use (include) the Airplane class
include "airplane.php";

//create new DeploymentTracker based on Airplane

class DeploymentTracker extends Airplane
{
  //add one method
  function refuel($amount)
  {
    $retValue = $this->model . " took on " . $amount . " of fuel.<br /> \n";
    return $retValue;
  } // end refuel

  //add another method
  function take_off($takeoffdate,$takeofftime)
  {
    $retValue = $this->model . " took off at $takeofftime on $takeoffdate<br /> \n";
    return $retValue;
  } // end take_off

  //override the setModel method
  function setModel($newModel)
  {
    $this->model = strtoupper($newModel);
  } // end setModel

} // end DeploymentTracker class def

//make an instance of the new airplane
$thePlane = new DeploymentTracker("F16 Eagle");

//DeploymentTracker has no constructor, so it uses its parent's constructor.

print "Aircraft model: " . $thePlane->getModel() . "<br /><br />\n";

//invoke new methods
print "The " . $thePlane->refuel("2,000 lb.");
print("<br />");
print "The " . $thePlane->take_off("3/15/2011","12:05:05");

?>
</body>
</html>

The Airplane Deployment page shows how inheritance works in these files.

Please note these points about the above page, which uses the Airplane class definition file and which inherits and extends that class:


Cloning an Object

Normally when you need to use an object, you create it as we have already seen in this handout.

But sometimes (usually very unoccasionally) you want to use a copy of an object that is already created and that already has some property values set just like you want them. In this kind of situation, you should consider using the object cloning feature of PHP.

As usual, there is an excellent Object Cloning Reference Page at the PHP.net site. I will summarize the key points here...

The basic syntax of cloning an object looks like this:

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. A "shallow copy" means that any properties that are references to other variables will remain references.

Once the cloning is complete, if a __clone() method is defined in the class, then the newly created object's __clone() method will be called, to allow any necessary changes to properties that need to be changed.

An example of how to do cloning is shown below. This is page airplaneCloning.php:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Airplane with Cloning</title>
  <style type="text/css">
    #mainDiv { width: 900px; font-family: Arial, sans-serif; margin: 0 auto; }
  </style>
</head>
<body>
  <div id="mainDiv">
<?php
  // Cloning an object

  //define the Airplane class
  class Airplane
  {

    var $model;
    var $color;

    function __construct($planeModel = "Piper Cub", $planeColor = "silver")
    {
      $this->model = $planeModel;
      $this->color = $planeColor;
    } // end constructor
    
    function __clone()
    {
      $this->setColor("Red, White, and Blue");
    }

    function setModel($newModel)
    {
      $this->model = $newModel;
    } // end setModel

    function getModel()
    {
      return $this->model;
    } // end getModel

    function setColor($newColor)
    {
      $this->color = $newColor;
    } // end setColor

    function getColor()
    {
      return $this->color;
    } // end getColor

  } // end Airplane class

  //make an instance of the Airplane
  $thePlane = new Airplane();

  //print original model
  print "The original plane...<br />\n";
  disp($thePlane, false);
  echo "<br />\n";

  print "Upgrading the fleet...<br />\n";
  $thePlane->setModel("McDonnell Douglas DC-10");
  disp($thePlane, false);
  echo "<br />\n";

  print "Cloning the plane...<br />\n";
  $clonedPlane = clone $thePlane;
  disp($clonedPlane, false);
  echo "<br />\n";

  function disp($data, $die=true)
  {
    echo "<pre>";
    var_dump($data);
    echo "</pre>";
    if ($die)
    {
      die("That's all, folks!");
    }
  }
?>
  </div>
</body>
</html>

You can see page airplaneCloning.php running here.

Please note these points about the above code page:


Objects in Session Variables

You may store an object in a session variable if needed. Here is some code that demonstrates how to store an object in a session variable.

First, let's make a new "include" file, airplane2.php:

<?php
//define the Airplane2 class
class Airplane2
{

  var $model;

  function __construct($handle = "Piper Cub")
  {
    $this->setModel($handle);
  } // end constructor

  function setModel($newModel)
  {
    $this->model = $newModel;
  } // end setModel

  function getModel()
  {
    return $this->model;
  } // end getModel

} // end Airplane2 class

?>

Here is the page which saves an object into a _SESSION variable. This is page airplaneStuff3.php:

<?php
  session_start();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Airplane with Methods</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
</head>
<body>
<?php
// Adding methods

//include the Airplane2 class
include "airplane2.php";

//make an instance of the Airplane
$thePlane = new Airplane2();

//Save the object in a session variable:
$_SESSION["myAirplane"] = $thePlane;

?>

<a href="airplaneStuff4.php">See the object used from the session variable.</a>
</body>
</html>

The second page, which is linked to from the first one, and which uses the _SESSION variable created in the first page, is airplaneStuff4.php:

<?php
  //The class definition needs to be included before session
  //capability is enabled.
  //The (packed) session version of the object will be "unpacked"
  //into useful form when session_start() is called:
  include 'airplane2.php';
  session_start();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
  <title>Airplane with Methods in a Session Variable</title>
  <meta http-equiv="content-type" content="text/html;charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
</head>
<body>

<?php

//Display the model directly from the session object:
print "Model directly from the session object: " .
      $_SESSION["myAirplane"]->getModel() . "<br /><br />\n";

//An alternative (indirect) way to do it:
//First ssign the object stored in the session variable,
//to a local variable:
$theNewAirplane = $_SESSION["myAirplane"];

//Second, display the model from the local object variable:
print "Model from a local object variable: " .
      $theNewAirplane->getModel() . "<br />\n";
?>

</body>
</html>

Please note these points about the above code pages:

You may see the above pages running here.


Anonymous Objects

Sometimes you can benefit from a feature of PHP called anonymous objects.

If you need an object that has no methods, meaning it has only properties, you may be able to use an anonymous object.

When you create an anonymous object, you still use the new keyword, but then instead of using a normal class name, you use the PHP built-in stdClass name, like this:

  $myObj = new stdClass();

Then you can assign properties to the new anonymous object like this:

  $myObj->firstname = 'Jim';
  $myObj->lastname = 'Link';
  $myObj->age = 39;
  $myObj->status = 'adjunct faculty instructor';

Quite often, an anonymous object is created in a function and then you return it from the function.

Also quite often, you echo the object in the context of a PHP page's being used as a data source for an AJAX call. In this situation, you normally need to convert the PHP object into a special string that is called a "JSON-encoded string", so that it can be transmitted across the internet to the calling/originating Web page. This kind of encoding often looks something like this:

  echo json_encode($myObj); 

where json_encode() is a built-in PHP function.


Why Use OOP?

Back to Top

Now let's talk about how OOP can help you improve the quality and efficiency of your PHP code.

Productivity

OOP can increase your productivity. What this statement really means is that you can save time or do more work in a given amount of time. After you create a class file, the next time you use it in a project, you will have automatically increased productivity, because you will have saved the time of having to go back and re-code something.

But why not just put some functions in an "include" file and use regular functions? The main reason is that when you re-use regular functions in a different project, you normally have to customize the functions so they work for the new project. In most cases, carefully programmed classes can save you the time spent in customizing regular functions.

Organization

OOP is a great way to keep your files structured and organized. Instead of entire code structures being embedded and spread out over numerous HTML pages, a single class file can be included in the various HTML pages. When you need to modify the class code, instead of your having to go to every page to change a variable or change how some HTML code is built or displayed, etc., you only have to modify the class file.

Should you use OOP?

Here are some situations in which you should use OOP:

But now here are some situations in which you should not use OOP:

But can you really be sure that OOP is not the way to go? A lot of PHP code gets reused eventually, even if you didn't originally think it would get reused.

Back to Top