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

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

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

Reproduced from Harry Fuecks' The PHP Anthology, Volume 1: Foundations by permission of SitePoint Pty. Ltd.. ISBN 0957921853, copyright 2003. All rights reserved.

Table of Contents

What are the basics of object oriented PHP?
Classes and Objects
Understanding Scope
A Three Liner
How do references work in PHP?
What Are References?
Using a Reference
The Importance of References
Good and Bad Practices
Performance Issues
References and PHP 5
How do I take advantage of inheritance?
Overriding
Inheritance in Action
How do objects interact?
Aggregation
Composition
Spotting the Difference
Polymorphism
Further Reading
The object oriented paradigm is an approach to programming that’s intended to encourage the development of maintainable and well structured applications. Many PHP coders regard object oriented programming (OOP) as some kind of mystic art, given that frequently, examples of PHP look only at procedural [1] approaches to problem solving. This is a shame, as there is much to be gained from adopting an object oriented approach to developing PHP applications, perhaps the most important being code reuse. A well written piece of object oriented code can easily be employed to solve the same problem in other projects; we can simply slot it in whenever we need it. There is a growing number of object oriented code repositories, such as PEAR and PHP Classes , which can save you from hours of work spent solving well charted problems, and leave you free to focus on the specifics of your application.

In this chapter, you’ll gain a practical grounding in writing object oriented PHP—and there’ll be plenty of opportunities to get your hands dirty. There are many ways to teach OOP, and the topic provides endless room for discussion. In my opinion, the best approach is to dive in head first, seeing how procedural tasks can be accomplished with classes in PHP, and adding the theory as we go. This is the approach we’ll take in this chapter. Throughout both volumes of The PHP Anthology, I’ll be using OOP, where appropriate, which should give you further examples to study. In particular, Chapter 7, Design Patterns should provide some insight into why OOP is an effective way to structure your applications.

In practice, learning to use the object model provided by PHP requires us to achieve two goals, which usually have to be undertaken simultaneously:

  • You’ll need to learn the PHP class syntax and object oriented terminology.

  • You must make the “mental leap” from procedural to object oriented code.

The first step is easy. It’s the subject of the next solution, and further examples appear in later solutions that look at more advanced subjects.

The second step, the “mental leap”, is both easy and challenging. Once you achieve it, you will no longer think about long lists of tasks that a single script should accomplish; instead, you’ll see programming as the putting together of a set of tools to which your script will delegate work.

Jumping ahead a little—to give you a taste of things to come—here’s a simple example that should be familiar to anyone who’s worked with PHP for more than a week: connecting to MySQL and fetching some data. A common procedural approach looks like this:

<?php
// Procedural Example
// Connect to MySQL
$connection = mysql_connect('localhost', 'harryf', 'secret');
// Select desired database
mysql_select_db('sitepoint', $connection);
// Perform a query selecting five articles
$sql = 'SELECT * FROM articles LIMIT 0,5';
$result = mysql_query($sql, $connection);
// Display the results
while ($row = mysql_fetch_array($result)) {
  // Display results here
}
?>

In the above script, we’ve called directly PHP’s MySQL functions, which act on the variables we pass to them. This generally results in our getting back a new variable with which we can perform further work.

An object oriented approach to solving the same problem might look like this:

<?php
// OOP Example
// Include MySQL class
require_once 'Database/MySQL.php';
// Instantiate MySQL class, connect to MySQL and select database
$db = new MySQL('localhost', 'harryf', 'secret', 'sitepoint');
// Perform a query selecting five articles
$sql = 'SELECT * FROM articles LIMIT 0,5';
$result = $db->query($sql); // Creates a MySQLResult object
// Display the results
while ($row = $result->fetch()) {
  // Display results here
}
?>

The detail of dealing with MySQL using PHP’s MySQL functions has now been delegated to an object that’s created from the MySQL class (which we’ll use frequently throughout this book, and which is constructed in Chapter 3, PHP and MySQL ). Although this example may not make entirely clear the advantages of OOP, given that, in terms of the amount of code, it’s very similar to the first example, what it does show is that some of the original script’s complexity is now being taken care of by the MySQL class.

For example, we now no longer need to perform two steps to connect to the MySQL server, and then select a database; rather, we can handle both steps in one when we create the MySQL object. Also, should we later wish to have the script fetch the results from a different database, such as PostgreSQL, we could use the relevant class that provided the same application programming interface (API) as the MySQL class—and, to do so, we’d only need to change a single line of the above example. We’ll do exactly that in Chapter 7, Design Patterns .

The object oriented approach really shows its worth in situations in which objects interact with each other. I’ll leave further discussion of that to the solutions in this chapter, but it’s an important concept. As you become fluent in object oriented programming, you’ll find that writing complex applications becomes as easy as putting together blocks of Lego.

I’ll introduce the occasional Unified Modelling Language (UML) class diagram in this discussion. UML is a standard for describing object oriented programs with images. Don’t worry if you haven’t come across UML before; the relationship between the diagrams and the code will speak for itself.

What are the basics of object oriented PHP?

Assuming you have no knowledge of OOP, the best place to start is with the basic PHP syntax for classes. You can think of a class simply as a collection of functions and variables.

Read The Fine Manual

The PHP manual contains a wealth of information on OOP:

https://www.php.net/oop

Here, we’ll develop a simple example that could help us generate HTML, which will demonstrate the basics of classes and objects in PHP. This isn’t intended to be an example of great design; it’s simply a primer in PHP syntax. Let’s begin with a procedural script that builds a Web page. Then we’ll gradually turn it into a PHP class:

Example 2.1. 1.php

<?php
// Generates the top of the page
function addHeader($page, $title)
{
  $page .= <<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1>$title</h1>
EOD;
  return $page;
}
// Generates the bottom of the page
function addFooter($page, $year, $copyright)
{
  $page .= <<<EOD
<div>&copy; $year $copyright</div>
</body>
</html>
EOD;
  return $page;
}
// Initialize the page variable
$page = '';
// Add the header to the page
$page = addHeader($page, 'A Prodecural Script');
// Add something to the body of the page
$page .= <<<EOD
<p>This page was generated with a procedural
script</p>
EOD;
// Add the footer to the page
$page = addFooter($page, date('Y'), 'Procedural Designs Inc.');
// Display the page
echo $page;
?>

Of note in this example is our first look at heredoc syntax , which is an alternative method of writing PHP strings. Instead of surrounding the text with quotes, you begin it with <<<EOD and a new line, and end it with a new line and then EOD. The PHP Manual can offer more detail on this if you're curious.

This procedural example uses two functions, addHeader and addFooter, along with a single global variable, $page. Perhaps this isn’t a far cry from procedural scripts you’ve written yourself; maybe you’ve included in every page a file that contains functions such as addHeader and addFooter.

But how do we refactor [2] the above code to take on an object oriented form? First, we need a class into which we can place the two functions, addHeader and addFooter:

Example 2.2. 2.php (excerpt)

<?php
// Page class
class Page {

  // Generates the top of the page
  function addHeader($page, $title)
  {
    $page .= <<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1>$title</h1>
EOD;
    return $page;
  }
  // Generates the bottom of the page
  function addFooter($page, $year, $copyright)
  {
    $page .= <<<EOD
<div>&copy; $year $copyright</div>
</body>
</html>
EOD;
    return $page;
  }
}

Using the PHP keyword class , we can group the two functions, addHeader and addFooter, within the class. Functions placed inside a class are known as member functions , or, more commonly, methods . Unlike normal functions, methods must be called as part of the class:


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

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