spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / phpanth2 / 1 To page 1current pageTo page 3To page 4To page 5To page 6To page 7
[previous][next]

Sr. Web Developer
mediabistro.com
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume
Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?


PHP Anthology, Volume 1, Chapter 2. Object Oriented PHP

Example 2.3. 2.php (excerpt)

// Initialize the page variable
$page = '';

// Add the header to the page
$page = Page::addHeader($page, 'A Script Using Static Methods');

// Add something to the body of the page
$page .= <<<EOD
<p align="center">This page was generated with static class
methods</p>
EOD;

// Add the footer to the page
$page = Page::addFooter($page, date('Y'), 'Static Designs Inc.');

// Display the page
echo $page;
?>

Here, we’ve called the class methods addHeader and addFooter using the :: operator. The script is practically the same as before; however, instead of calling our functions directly, we need to call them as shown here:

$page = Page::addHeader($page, 'A Script Using Static Methods');

Although this isn’t a big improvement, it does let us collect our functions together by their job description. This allows us to call different functions by the same name, each nested separately inside a different class.

Classes and Objects

A class is a “blueprint” for an object. That is, unlike a function that you’d declare and use, a class merely describes a type of object. Before you can do useful work with it, you need to create an object —an instance of the class—using a process called instantiation . Once you have an object, you can call the methods that are defined in the class.

Classes don’t contain only functions—they can also contain variables. To make the Page class we developed above more useful, we might want to group some variables with the methods, then instantiate the class into an object. Here’s the code for the revamped Page class; join me below for the explanation:

Example 2.4. 3.php (excerpt)

<?php
// Page class
class Page {

  // Declare a class member variable
  var $page;

  // The constructor function
  function Page()
  {
    $this->page = '';
  }

  // Generates the top of the page
  function addHeader($title)
  {
    $this->page .= <<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
  }

  // Adds some more text to the page
  function addContent($content)
  {
    $this->page .= $content;
  }

  // Generates the bottom of the page
  function addFooter($year, $copyright)
  {
    $this->page .= <<<EOD
<div align="center">&copy; $year $copyright</div>
</body>
</html>
EOD;
  }

  // Gets the contents of the page
  function get()
  {
    return $this->page;
  }
}

The Page class has become a lot more useful in this version of the example. First of all, we’ve added a member variable (also called a field ), in which to store the HTML:

  // Declare a class member variable
  var $page;

The PHP keyword var is used to declare variables in classes. We can also assign values to variables as we declare them, but we cannot place function calls in the declaration. For example:

  // This is allowed
  var $page = '';
  // This is NOT allowed
  var $page = strtolower('HELLO WORLD');

After the variable declaration, we have a special method called the constructor . This method is automatically executed when the class is instantiated. The constructor function must always have the same name as the class.

Inside the constructor we’ve used a special variable, $this :

  // The constructor function
  function Page()
  {
    $this->page = '';
  }

Within any method (including the constructor) $this points to the object in which the method is running. It allows the method to access the other methods and variables that belong to that particular object. The -> (arrow) operator that follows $this is used to point at a property or method that’s named within the object.

In the example above, the constructor assigns an empty string value to the $page member variable we declared at the start. The idea of the $this variable may seem awkward and confusing to start with, but it’s a common strategy employed by other programming languages, such as Java, to allow class members to interact with each other. You’ll get used to it very quickly once you start writing object oriented PHP code, as it will likely be required for almost every method your class contains.

Of the other class methods, addHeader and addFooter are almost the same as before; however, notice that they no longer return values. Instead, they update the object’s $page member variable, which, as you’ll see, helps simplify the code that will use this class. We’ve also used the addContent method here; with this, we can add further content to the page (e.g. HTML that we’ve formatted ourselves, outside the object). Finally, we have the get method, which is the only method that returns a value. Once we’ve finished building the page, we’ll use this to create the HTML.

All these methods access the $page member variable, and this is no coincidence. The ability to tie PHP code (the methods) to the data (the variables) that it works on is the most fundamental feature of object oriented programming.

Here’s the class in action:

Example 2.5. 3.php (excerpt)

// Instantiate the Page class
$webPage = new Page();

// Add the header to the page
$webPage->addHeader('A Page Built with an Object');

// Add something to the body of the page
$webPage->addContent("<p> align=\"center\">This page was " .
  "generated using an object</p>\n");

// Add the footer to the page
$webPage->addFooter(date('Y'), 'Object Designs Inc.');

// Display the page
echo $webPage->get();
?>

To use the class, we’ve instantiated it with the new keyword. The object created from the class is placed in the $webPage variable. Through this variable, we have access to all the members of the object as we did with the $this variable above.

The first call to the addHeader method demonstrates the point:

$webPage->addHeader('A Page Built with an Object');

Only at the end, upon calling the get method, do we actually get anything back from the class. No longer do we need to worry about passing around a variable that contains the contents of the page—the class takes care of that.

Notice also that the number of lines of code we have to write to use the class is fewer than were required in the earlier examples. Although it’s impossible to determine good application design by counting the number of lines of code, it is clear that the class has made the procedural code that uses it much simpler. From the point of view of people reading the code, it’s already fairly clear what’s going on, even without them having to look at the code for the Page class

home / programming / phpanth2 / 1 To page 1current pageTo page 3To page 4To page 5To page 6To page 7
[previous][next]

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business

Created: March 27, 2003
Revised: January 2, 2004

URL: http://webreference.com/programming/phpanth2