Article

The PHP Anthology Volume 1, Chapter 2 - Object Oriented PHP

Page: 1 2 3 4 5 6 7 8 9 10 11 Next

Using the class externally is now even easier:

Example 2.7. 4.php (excerpt)

// Instantiate the page class    
$webPage = new Page('As Easy as it Gets', date('Y'),    
 'Easy Systems Inc.');    
   
// Add something to the body of the page    
$webPage->addContent(    
 "<p align=\"center\">It's so easy to use!</p>\n");    
   
// Display the page    
echo $webPage->get();    
?>

Essentially, the page is now built using only three lines of code; I can also reuse this class to generate other pages. Represented as a UML diagram, the Page class is shown in Figure 2.1.

1264_pageclass
Figure 2.1. Page Class as UML

The member variables appear in the middle area, while methods appear in the bottom box. Also, the plus and minus signs are there to indicate to other developers which elements of the class are public (+) and which are private (-). Unlike languages such as Java, PHP does not enforce privacy on objects (enforced privacy constraints on class members will be added in PHP 5.0.); in the examples above, we could have accessed the $page member variable directly in our main script. Because we want the object to handle its own data without outside interference, we indicate in the UML diagram that only those members that have a + against them are available for public use. Those with a - are purely for internal use within the class.

That covers the basics of the class syntax in PHP, and should give you an idea of how classes compare with procedural code. With the syntax you’ve learnt, you should be able to write standalone classes containing the variables and functions you use frequently—a task that can really help tidy up your code and make it easier to maintain. This is a great start, but the real power of object oriented programming comes from using multiple objects and classes together. The rest of this chapter will look at some of the more advanced facets of the PHP object model, including references, inheritance, aggregation, and composition.

How do references work in PHP?

Most discussions of references in PHP begin with an opener like “references are confusing,” which may add to the myth that surrounds them. In fact, references are a very simple concept to grasp, yet they’re a concept that self-taught PHP developers only really need to consider once they begin writing object oriented applications. Until then, you’re probably oblivious to the way PHP handles variables behind the scenes. Much of the confusion that exists around references has more to do with developers who are experienced with other languages like C++ or Java trying to work with PHP: Java, in particular, handles object references in almost the opposite way to the approach PHP takes in version 4.

References vs. Pointers

Developers who are familiar with compiled languages such as C++ or Java should note that references in PHP are not analogous to pointers in other languages.

A pointer contains an address in memory that points to a variable, and must be dereferenced in order to retrieve the variable’s contents.

In PHP, all variable names are linked with values in memory automatically. Using a reference allows us to link two variable names to the same value in memory, as if the variable names were the same. You can then substitute one for the other.

What Are References?

To understand references, we have to begin by understanding how PHP handles variables under normal circumstances (i.e. without references).

By default, when a variable is passed to anything else, PHP creates a copy of that variable. When I say “passed,” I mean any of the following:

1. Passing a variable to another variable:

<?php    
 $color = 'blue';    
 $settings['color'] = $color;    
?>

$settings['color'] now contains a copy of $color.

2. Passing a variable as an argument to a function:

<?php    
function isPrimaryColor($color)    
{    
 // $color is a copy    
 switch ($color) {    
   case 'red':    
   case 'blue':    
   case 'green':    
     return true;    
     break;    
   default:    
     return false;    
 }    
}    
   
$color = 'blue';    
if (isPrimaryColor($color)) {    
 echo $color . ' is a primary color';    
} else {    
 echo $color . ' is not a primary color';    
}    
?>

When $color is passed to the function isPrimaryColor, PHP works with a copy of the original $color variable inside the function.

3. The same applies when passing variables to class methods:

<?php    
class ColorFilter {    
 var $color;    
 function ColorFilter($color)    
 {    
   // $color is a copy    
   $this->color = $color;    
   // $this->color is a copy of a copy    
 }    
 function isPrimaryColor()    
 {    
   switch ($this->color) {    
     case 'red':    
     case 'blue':    
     case 'green':    
       return true;    
       break;    
     default:    
       return false;    
   }    
 }    
}    
   
$color = 'blue';    
$filter = new ColorFilter($color);    
if ($filter->isPrimaryColor() ) {    
   echo ($color.' is a primary color');    
} else {    
   echo ($color.' is not a primary color');    
}    
?>

The original $color outside the class is passed to ColorFilter’s constructor. The $color variable inside the constructor is a copy of the version that was passed to it. It’s then assigned to $this->color, which makes that version a copy of a copy.

All of these means of passing a variable create a copy of that variable’s value; this is called passing by value.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links