Professional Documents
Culture Documents
PHP
Advanced
and Object-Oriented
Programming
Larry Ullman
Peachpit Press
Visual QuickPro Guide
PHP Advanced and Object-Oriented Programming
Larry Ullman
Peachpit Press
1249 Eighth Street
Berkeley, CA 94710
Find us on the Web at: www.peachpit.com
To report errors, please send a note to: errata@peachpit.com
Peachpit Press is a division of Pearson Education.
Copyright © 2013 by Larry Ullman
Acquisitions Editor: Rebecca Gulick
Production Coordinator: Myrna Vladic
Copy Editor: Liz Welch
Technical Reviewer: Alan Solis
Compositor: Danielle Foster
Proofreader: Patricia Pane
Indexer: Valerie Haynes Perry
Cover Design: RHDG / Riezebos Holzbaur Design Group, Peachpit Press
Interior Design: Peachpit Press
Logo Design: MINE™ www.minesf.com
Notice of Rights
All rights reserved. No part of this book may be reproduced or transmitted in any form by any
means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written
permission of the publisher. For information on getting permission for reprints and excerpts,
contact permissions@peachpit.com.
Notice of Liability
The information in this book is distributed on an “As Is” basis, without warranty. While every
precaution has been taken in the preparation of the book, neither the author nor Peachpit Press
shall have any liability to any person or entity with respect to any loss or damage caused or
alleged to be caused directly or indirectly by the instructions contained in this book or by the
computer software and hardware products described in it.
Trademarks
Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson Education.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in this book, and Peachpit was aware of
a trademark claim, the designations appear as requested by the owner of the trademark. All other
product names and services identified throughout this book are used in editorial fashion only and
for the benefit of such companies with no intention of infringement of the trademark. No such use,
or the use of any trade name, is intended to convey endorsement or other affiliation with this book.
13-digit ISBN: 978-0-321-83218-4
10-digit ISBN: 0-321-83218-3
987654321
Printed and bound in the United States of America
Dedication
To my good friend Michael K. and his family: I cannot thank you all
enough for your continuing friendship, generosity, and kindness over
these many years.
My utmost thanks to…
Jessica, the love of my life, for just about everything.
Zoe and Sam, for making my world a better place.
Everyone at Peachpit Press for their support, for their dedication to
putting out quality books, and for everything else they do to make all
this happen.
The most excellent editor, Rebecca Gulick, for so many reasons.
Liz Welch, for her spot-on copyediting and attention to detail.
The production coordinator, Myrna Vladic, the compositor, Danielle Foster,
the proofreader, Patricia Pane, and the indexer, Valerie Haynes Perry, who
turn my mess of files into an actual book.
Alan Solis, for his very, very helpful technical review.
Thomas Larsson, for his input on the design patterns chapter. Always
helpful to get even one more extra set of eyes!
Tjobbe Andrews (http://tawd.co.uk), for volunteering to create a
new HTML5 design for the example chapter. And for doing so on such
short notice!
Sara, for entertaining the kids so that I can get some work done, even
if I’d rather not.
The readers, the readers, the readers!
Table of Contents
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . ix
Table of Contents v
Chapter 5 Advanced OOP . . . . . . . . . . . . . . . . . . . . . . 149
Advanced Theories . . . . . . . . . . . . . . . . . . . . . 150
Inheriting Classes . . . . . . . . . . . . . . . . . . . . . . 152
Inheriting Constructors and Destructors . . . . . . . . . 157
Overriding Methods . . . . . . . . . . . . . . . . . . . . . 161
Access Control . . . . . . . . . . . . . . . . . . . . . . . 165
Using the Scope Resolution Operator . . . . . . . . . . 172
Creating Static Members . . . . . . . . . . . . . . . . . . 176
Review and Pursue . . . . . . . . . . . . . . . . . . . . . 182
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
Introduction ix
This book can be loosely divided into three Unlike with most of my other books, I do
sections. The first three chapters cover not expect that you’ll necessarily read this
advanced PHP knowledge in general: pro- book in sequential order, for the most part.
gramming techniques, Web applications, Some chapters do assume that you’ve
and databases. Those chapters all cover read others, like the object-oriented ones,
information that the average PHP program- which have a progression to them. Some
mer may not be familiar with but should be later chapters also reference examples
able to comprehend. In the process, you’ll completed in earlier ones. If you read the
pick up lots of useful code, too. later ones first, you’ll just need to skip
The next six chapters focus on object- back over to the earlier ones to gener-
oriented programming. This section ate whatever database or scripts the later
constitutes about half of the book. OOP is chapter requires.
explained starting with the fundamentals, Finally, I’ll be using HTML5 in my scripts
then going into lots of advanced topics, and instead of HTML. I’ll also use some CSS, as
ending with plenty of real-world examples. warranted. I do not discuss either of these
The final five chapters are all “PHP and…” subjects in this book (and, to be frank, may
chapters: not adhere to them perfectly). If you are
not already familiar with the subjects, you
n Communicating with networked servers should look at some online resources or
n Communicating with the host server good books (such as Elizabeth Castro’s
n Using the command-line interface excellent Visual QuickStart Guides) for
more information.
n XML
n Debugging, testing, and performance
Most examples used in this book are
intended to be applicable in the real world,
omitting the frivolous code you might see in
other books, tutorials, and manuals. I focus
almost equally on the philosophies involved
as on the coding itself so that, in the end,
you will come away with not just how to do
this or that but also how to apply the new
skills and ideas to your own projects.
x Introduction
What’s new in this edition What You’ll Need
I had three goals in writing this new edition:
Just as this book assumes that you already
n Greatly expanding the coverage possess the fundamental skills to program
of OOP in PHP (and, more important, to debug it
n Introducing new, more current topics, when things go awry), it also assumes that
such as unit testing and debugging you already have everything you need to
follow along with the material. For starters,
n Cutting content that is outdated or
this means a PHP-enabled server. As of this
has since been better covered in my
writing, the latest version of PHP was 5.4,
other books
and much of the book depends on your
In terms of additional new material, by far using at least PHP 5.3.
the biggest change has been the additional
Along with PHP, you’ll often need a
coverage of object-oriented programming,
database application. I use MySQL for the
including a chapter on design patterns.
examples, but you can use anything. And,
There’s also a new example chapter that
for the scripts in some of the chapters to
uses objects instead of procedural code.
work—particularly the last five—your PHP
Of course, all of the code and writing has installation will have to include support
been refreshed, edited, and improved as for the corresponding technology, and
needed. This could mean just switching to that technology’s library may need to be
HTML5 and better use of CSS, or my doing installed, too. Fortunately, PHP 5 comes
a better job of explaining complex ideas with built-in support for many advanced
and examples. features. If the scripts in a particular chap-
ter require special extensions, that will be
How this book compares referenced in the chapter’s introduction.
to my others This includes the few times where I make
use of a PEAR or PECL class. Nowhere in
Those readers who have come to this book
this book will I discuss installation of PHP,
from my PHP for the Web: Visual Quick-
MySQL, and a Web server, though, as I
Start Guide (Peachpit Press, 2011) may find
expect you should already know or have
themselves in a bit over their heads. This
accomplished that.
book does assume complete comfort with
standard PHP programming, in particular Should you have questions or problems,
debugging your own scripts. I’m not sug- you can always search the Web or post a
gesting you put this book down, but if you message in my support forums (www.Larry
find it goes too fast for you or assumes Ullman.com/forums/) for assistance.
knowledge you don’t currently possess, you Beyond PHP, you need the things you
may want to check out my PHP and MySQL should already have: a text editor or IDE,
for Dynamic Web Sites: Visual QuickPro an FTP application (if using a remote
Guide (Peachpit Press, 2011) instead. server), and a Web browser. All of the
If you have read the PHP and MySQL code in this book has been tested on both
book, or a previous edition of this one, I’m Windows XP and Mac OS X; you’ll see
hoping that you’ll find this to be a wonder- screen shots in both operating systems.
ful addition to your library and skill set.
Introduction xi
Support Web Site
I have developed a Web site to support this
book, available at www.LarryUllman.com.
This site:
n Has every script available for download
n Has the SQL commands available for
download
n Has extra files, as necessary, available
for download
n Lists errors that have been found in
the book
n Features a support forum where you
can get help or assist others
n Provides a way to contact me directly
I’ll also post at the site articles that extend
some of the information covered in
this book.
When using this site, please make sure
you’ve gone to the correct URL (the book’s
title and edition are plastered everywhere).
Each book I’ve written has its own sup-
port area; if you go to the wrong one, the
downloadable files won’t match those in
the book.
xii Introduction
4
Basic
Object-Oriented
Programming
Although PHP is still not as strong in its
OOP feature set as other languages, In This Chapter
object-oriented programming in PHP has
a lot going for it. And while it is possible to OOP Theory 120
have a good career without learning and Defining a Class 121
using OOP, you should familiarize yourself
Creating an Object 124
with the concept. At the very least, being
able to use both OOP and procedural pro- The $this Attribute 127
gramming allows you to better choose the Creating Constructors 133
right approach for each individual project.
Creating Destructors 136
In this chapter, and the next (Chapter 5,
Designing Classes with UML 140
“Advanced OOP”), I will explain not only
the syntax of OOP in PHP 5 and later, but Better Documentation with
the key underlying OOP theories as well. In phpDocumentor 143
this chapter, I will use somewhat mundane Review and Pursue 148
examples, but in subsequent chapters,
practical, real-world code will be used.
Through multiple examples and plenty of
explanation, I hope in this book to fully
demonstrate not just how you do object-
oriented programming in PHP but also
when and why.
OOP Theory Related to modularity is abstraction:
classes should be defined broadly. This is
The first thing that you must understand a common and understandable beginner’s
about OOP is that it presents not just new mistake. As an example, instead of design-
syntax but a new way of thinking about a ing a class for interacting with a MySQL
problem. By far the most common mistake database, you should make one that
beginning OOP programmers make is to interacts with a nonspecific database. From
inappropriately apply OOP theory. PHP will there, using inheritance and overriding,
tell you when you make a syntactical mis- you would define a more particular class
take, but you’ll need to learn how to avoid for MySQL. This class would look and act
theoretical mistakes as well. To explain… like the general database class, but some
All programming comes down to taking of its functionality would be customized.
actions with data: a user enters data in Another principle of OOP is encapsulation:
an HTML form; the PHP code validates it, separating out and hiding how something
emails it, and stores it in a database; and so is accomplished. A properly designed class
forth. These are simply verbs (actions) and can do everything you need it to do with-
nouns (data). With procedural programming, out your ever knowing how it’s being done.
the focus is on the verbs: do this, then this, Coupled with encapsulation is access
then this. In OOP, the focus is on the nouns: control or visibility, which dictates how
with what types of things will the applica- available components of the class are.
tion work? In both approaches, you need Those are the main concepts behind OOP.
to identify both the nouns and the verbs You’ll see how they play out in the many
required; the difference is in the focus of the OOP examples in this book. But before
application’s design. getting into the code, I’ll talk about OOP’s
The two most important terms for OOP are dark side.
class and object. A class is a generalized First of all, know that OOP is not a better
definition of a thing. Think of classes as way to program, just a different way. In
blueprints. An object is a specific imple- some cases, it may be better and in some
mentation of that thing. Think of objects cases worse.
as the house built using the blueprint as a
guide. To program using OOP, you design As for the technical negatives of OOP,
your classes and then implement them as use of objects can be less efficient than a
objects in your programs when needed. procedural approach. The performance dif-
ference between using an object or not may
One of the tenets of OOP is modularity: be imperceptible in some cases, but you
breaking applications into specific subparts. should be aware of this potential side effect.
Web sites do many, many things: interact
with databases, handle forms, send emails, A second issue that arises is what I have
generate HTML, etc. Each of these things already pointed out: misuse and overuse
can be a module, which is to say a class. of objects. Whereas bad procedural pro-
By separating unrelated (albeit interacting) gramming can be a hurdle to later fix, bad
elements, you can develop code indepen- OOP can be a nightmare. However, the
dently, make maintenance and updates less information taught over the next several
messy, and simplify debugging. chapters should prevent that from being
the case for you.
120 Chapter 4
Defining a Class Attributes within classes are a little dif-
ferent than variables outside of classes.
OOP programming begins with classes, a First, all attributes must be prefixed with a
class being an abstract definition of a thing: keyword indicating the variable’s visibility.
what information must be stored and what The options are public, private, and
functionality must be possible with that protected. Unfortunately, these values
information? A User class would be able to won’t mean anything to you until you
store information such as the user’s name, understand inheritance (in Chapter 5),
ID, email address, and so forth. The func- so until then, just use public:
tionality of a User could be login, logout, class ClassName {
change password, and more.
public $var1, $var2;
Syntactically, a class definition begins with
function functionName() {
the word class, followed by the name
of the class. The class name cannot be // Function code.
a reserved word and is often written in }
uppercase, as a convention. After the class
}
name, the class definition is placed within
curly braces: As shown here, a class’s attributes are
class ClassName {
listed before any method definitions.
}
The second distinction between attributes
and normal variables is that if an attribute
Classes contain variables and functions, is initialized with a set value, that value
which are referred to as attributes (or must be a literal value and not the result
properties) and methods, respectively of an expression:
(you’ll see other terms, too). Collectively, a
class GoodClass {
class’s attributes and methods are called
its members. public $var1 = 123;
Functions are easy to add to classes: public $var2 = 'string';
class ClassName { public $var3 = array(1, 2, 3);
function functionName() { }
// Function code. class BadClass {
} // These won't work!
} public $today = get_date();
The methods you define within a class public $square = $num * $num;
are defined just like functions outside of }
a class. They can take arguments, have
default values, return values, and so on.
122 Chapter 4
3. Begin defining the first (and only) method: break;
function sayHello($language = case 'English':
➝ 'English') { default:
This class currently contains no attri- echo 'Hello, world!';
butes (variables), as those would have
break;
been declared before the methods.
This method is called sayHello(). It } // End of switch.
takes one argument: the language for The switch prints different messages
the greeting. based upon the chosen language.
For the methods, I normally use the English is the default language, both
“lowercase camel” convention: start in the switch and as the value of the
with lowercase letters, separating $language argument (see Step 3). Obvi-
words with an uppercase letter. This is ously you can easily expand this switch
another common convention, although to include more languages, like non-
not one as consistently followed as that Western ones.
for the class name itself. 6. Complete the sayHello() method:
4. Start the method’s code: echo '</p>';
echo '<p>'; } // End of sayHello() method.
The method will print Hello, world! in You just need to close the HTML para-
one of several languages. The message graph tag.
will be wrapped within HTML paragraph
7. Complete the class and the PHP page:
tags, begun here.
}
5. Add the method’s switch:
switch ($language) {
8. Save the file as HelloWorld.php.
124 Chapter 4
Script 4.2 In this page, PHP uses the defined class 2. Include the class definition:
in order to say Hello, world! in several different
languages. require('HelloWorld.php');
126 Chapter 4
The $this Attribute The issue is that within the class itself (i.e.,
within a class’s methods), you must use
The HelloWorld class actually does some- an alternative syntax to access the class’s
thing, which is nice, but it’s a fairly minimal attributes. You cannot do just this:
example. The class includes a method, but it class BadClass {
does not contain any attributes (variables).
public $var;
As I say in the section “Defining a Class,”
function do() {
attributes:
// This won't work:
n Are variables
print $var;
n Must be declared as public, private,
or protected (I’ll use only public in }
this chapter) }
n If initialized, must be given a static value The do() method cannot access $var
(not the result of an expression) in that manner. The solution is a special
Those are the rules for defining a class’s variable called $this. The $this variable
attributes, but using those attributes in a class always refers to the current
requires one more piece of information. instance (i.e., the object involved) of that
As already explained, through the object, class. Within a method, you can refer to
you can access attributes via the object the instance of a class and its attributes by
notation operator (->): using the $this->attributeName syntax.
$object->propertyName; Rather than over-explaining this concept,
I’ll go right into another example that puts
this new knowledge into action. This next,
much more practical, example will define a
class representing a rectangle.
128 Chapter 4
Script 4.3 continued 5. Create a method that calculates and
returns the rectangle’s area:
38 } else {
39 return false; // Not a square function getArea() {
40 }
41 } return ($this->width *
42 ➝ $this->height);
43 } // End of Rectangle class.
}
This method doesn’t need to take any
arguments, because it can access the
class’s attributes via $this. Calculat-
ing the area of a rectangle is simple:
multiply the width times the height.
This value is then returned.
6. Create a method that calculates and
returns the rectangle’s perimeter:
function getPerimeter() {
return ( ($this->width +
➝ $this->height) * 2 );
}
This method is like getArea(), except it
uses a different formula.
7. Create a method that indicates if the
rectangle is also a square:
function isSquare() {
if ($this->width ==
➝ $this->height) {
return true;
} else {
return false;
}
}
This method compares the rectangle’s
dimensions. If they are the same, the
Boolean true is returned, indicating the
rectangle is a square. Otherwise, false
is returned.
8. Complete the class:
} // End of Rectangle class.
9. Save the file as Rectangle.php.
130 Chapter 4
Script 4.4 The Rectangle class is used in this PHP script. The rectangle’s dimensions are first assigned to the
class’s attributes by invoking the setSize() method, and then various properties of the rectangle are reported.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Rectangle</title>
6 <link rel="stylesheet" href="style.css">
7 </head>
8 <body>
9 <?php # Script 4.4 - rectangle1.php
10 /* This page uses the Rectangle class.
11 * This page shows a bunch of information about a rectangle.
12 */
13
14 // Include the class definition:
15 require('Rectangle.php');
16
17 // Define the necessary variables:
18 $width = 42;
19 $height = 7;
20
21 // Print a little introduction:
22 echo "<h2>With a width of $width and a height of $height...</h2>";
23
24 // Create a new object:
25 $r = new Rectangle();
26
27 // Assign the rectangle dimensions:
28 $r->setSize($width, $height);
29
30 // Print the area:
31 echo '<p>The area of the rectangle is ' . $r->getArea() . '</p>';
32
33 // Print the perimeter:
34 echo '<p>The perimeter of the rectangle is ' . $r->getPerimeter() . '</p>';
35
36 // Is this a square?
37 echo '<p>This rectangle is ';
38 if ($r->isSquare()) {
39 echo 'also';
40 } else {
41 echo 'not';
42 }
43 echo ' a square.</p>';
44
45 // Delete the object:
46 unset($r);
47
48 ?>
49 </body>
50 </html>
132 Chapter 4
Creating Constructors Because the constructor is still just another
method, it can take arguments, and values
A constructor is a special kind of method that for those arguments can be provided when
differs from standard ones in three ways: the object is created:
n Its name is always _ _construct(). class User {
n It is automatically and immediately function _ _construct($id) {
called whenever an object of that class // Function code.
is created.
}
n It cannot have a return statement.
}
The syntax for defining a constructor is
$me = new User(2354);
therefore
class ClassName {
The Rectangle class could benefit from hav-
ing a constructor that assigns the rectangle’s
public $var; dimensions when the rectangle is created.
function _ _construct() {
// Function code. To add and use a constructor:
} 1. Open Rectangle.php (Script 4.3) in your
text editor or IDE.
}
2. After declaring the attributes and before
A constructor could be used to connect to
defining the setSize() method, add the
a database, set cookies, or establish initial
constructor (Script 4.5):
values. Basically, you’ll use constructors to do
whatever should always be done—and done function _ _construct($w = 0,
first—when an object of this class is made. ➝ $h = 0) {
$this->width = $w;
$this->height = $h;
}
continues on next page
Script 4.5 A constructor has been added to the Rectangle class. This makes it possible to assign the
rectangle’s dimensions when the object is created.
134 Chapter 4
Script 4.6 This new version of the script assigns 8. Save the file as rectangle2.php, place
the rectangle’s dimensions when the object is
it in your Web directory along with the
created (thanks to the constructor).
new Rectangle.php (Script 4.5), and
1 <!doctype html> test in your Web browser A.
2 <html lang="en">
3 <head>
4 <meta charset="utf-8"> A constructor like the one just added
5 <title>Rectangle</title> to the Rectangle class is called a default
6 <link rel="stylesheet" constructor, as it provides default values for
➝ href="style.css">
its arguments. This means that a Rectangle
7 </head>
8 <body>
object can be created using either of these
9 <?php # Script 4.6 - rectangle2.php techniques:
10 /* This page uses the revised Rectangle $r = new Rectangle($width, $height);
➝ class.
11 * This page shows a bunch of $r = new Rectangle();
➝ information
12 * about a rectangle. You can directly call a constructor
13 */ (although you will rarely need to):
14
15 // Include the class definition: $o = new SomeClass();
16 require('Rectangle.php');
17 $o->_ _construct();
18 // Define the necessary variables:
19 $width = 160; With the Rectangle example, this would let
20 $height = 75; you get rid of the setSize() method without
21 losing the ability to resize a rectangle.
22 // Print a little introduction:
23 echo "<h2>With a width of $width and a In PHP 4 and in other programming
➝ height of $height...</h2>"; languages (like C++), a constructor is declared
24
by creating a method whose name is the same
25 // Create a new object:
26 $r = new Rectangle($width, $height);
as the class itself.
27
28 // Print the area. If PHP 5 cannot find a _ _construct()
29 echo '<p>The area of the rectangle method in a class, it will then try to find a con-
➝ is ' . $r->getArea() . '</p>'; structor whose name is the same as the class
30 (the PHP 4 constructor naming scheme).
31 // Print the perimeter.
32 echo '<p>The perimeter of the rectangle
➝ is ' . $r->getPerimeter() . '</p>';
33
34 // Is this a square?
35 echo '<p>This rectangle is ';
36 if ($r->isSquare()) {
37 echo 'also';
38 } else {
39 echo 'not';
40 }
41 echo ' a square.</p>';
42
43 // Delete the object: A The resulting output is not affected by
44 unset($r); the incorporation of a constructor in the
45 Rectangle class.
46 ?>
47 </body>
48 </html>
136 Chapter 4
To create a destructor: 3. Create the constructor:
1. Create a new PHP document in your function _ _construct() {
text editor or IDE, to be named demo. echo '<p>In the constructor.</p>';
php, beginning with the standard HTML
}
(Script 4.7):
<!doctype html>
The constructor doesn’t do anything
but print a message indicating that it
<html lang="en"> has been invoked. This will allow you to
<head> trace when the class’s automatic meth-
ods are called.
<meta charset="utf-8">
4. Create the destructor:
<title>Constructors and
➝ Destructors</title> function _ _destruct() {
<link rel="stylesheet" echo '<p>In the destructor.</p>';
➝ href="style.css"> }
</head> 5. Complete the class:
<body> }
<?php # Script 4.7 - demo.php It’s a very simple class!
2. Begin defining the class: continues on next page
class Demo {
To make this example even simpler,
I’ll define and use the class in the
same script.
Script 4.7 This script doesn’t do anything except best convey when constructors and destructors are called.
1 <!doctype html>
2 <html lang="en">
3 <head>
4 <meta charset="utf-8">
5 <title>Constructors and Destructors</title>
6 <link rel="stylesheet" href="style.css">
7 </head>
8 <body>
9 <?php # Script 4.7 - demo.php
10 /* This page defines a Demo class
11 * and a demo() function.
12 * Both are used to show when
13 * constructors and destructors are called.
14 */
15
138 Chapter 4
After the object is created in the func-
tion, the About to leave the function.
message is printed. Then the function is
exited, at which point in time the object
defined in the function—$f—goes away,
A The flow of thus invoking the $f object’s destructor,
the two objects’
creation and printing In the destructor.
destruction over 9. Delete the $o object:
the execution
of the script is echo '<p>About to delete the
revealed by this
➝ object...</p>';
script. In particular,
you can see unset($o);
how the test()
function’s object, Once this object is deleted, its destruc-
$f, lives and dies
tor is invoked.
in the middle of
this script. 10. Complete the page:
echo '<p>End of the script.</p>';
?>
</body>
</html>
11. Save the file as demo.php and place it in
B If you don’t your Web directory. Then test by view-
forcibly delete the
object A, it will ing it in your Web browser A.
be deleted when
the script stops 12. Delete the unset($o) line, save the file,
running. This and rerun it in your Web browser B.
means that the $o
object’s destructor Also check the HTML source code
is called after of this page C to really understand
the final printed
message, even
the flow.
after the closing (Arguably, you could also delete the
HTML tags C.
About to delete the object… line,
although I did not for the two figures.)
140 Chapter 4
With this in mind, you can complete the
class diagram for the HelloWorld class B.
In the next steps, you’ll design the diagram
B A UML representation of the simple that reflects the Rectangle class.
HelloWorld class.
142 Chapter 4
Better Documentation Although you can adequately document
your code using simple comments, as I do
with phpDocumentor in this book, there are two obvious ben-
efits to adopting a formal phpDocumentor
Along with creating a UML class design, approach:
another new topic in this edition is
n It conveys many best practices and
creating better code documentation
recommended styles.
using phpDocumentor (www.phpdoc.org).
n phpDocumentor will generate docu-
In my opinion, properly documenting one’s
mentation, in HTML and other formats,
code is so vitally important that I wish PHP
for you.
would generate errors when it came across
a lack of comments! Having taught PHP The generated HTML A can also be a
and interacted with readers for years, I am valuable resource for anyone using your
amazed at how often programmers omit code, particularly your classes.
comments, occasionally under the guise of
waiting until later. Proper documentation is
something that should be incorporated into
code for your own good, for your client’s,
for your co-workers’ (if applicable), and
for the programmer in the future who may
have to alter or augment your work—even
if that programmer is you.
144 Chapter 4
Script 4.8 continued To document a variable declaration, you
use the @var tag, followed by the variable’s
25 function sayHello($language =
➝ 'English') { type (and optional description):
26 /**
27 // Put the greeting within P tags:
28 echo '<p>'; * @var string
29
*/
30 // Print a message specific to a
➝ language: $name = 'Larry Ullman';
31 switch ($language) {
32 case 'Dutch': Notice that the docblock doesn’t need
33 echo 'Hallo, wereld!'; to reference the variable name, as php-
34 break; Documentor will be able to read that from
35 case 'French': the following line of code. The point of
36 echo 'Bonjour, monde!';
the docblock is to indicate the variable’s
37 break;
38 case 'German': intended type.
39 echo 'Hallo, Welt!'; To document methods and functions, use
40 break;
@param to detail the function’s parameters
41 case 'Italian':
42 echo 'Ciao, mondo!'; and @return to indicate the type of value
43 break; the function returns (Script 4.8).
44 case 'Spanish':
The details as to the possible types, and
45 echo '¡Hola, mundo!';
46 break; the full usage of all of phpDocumentor,
47 case 'English': can be found in the documentation
48 default: (www.phpdoc.org/docs/).
49 echo 'Hello, world!';
50 break; Once you’ve written comments in the
51 } // End of switch. proper format, you can use the phpDocu-
52 mentor tool to generate your documen-
53 // Close the HTML paragraph: tation. To do that, you must first install
54 echo '</p>';
phpDocumentor. The best way to install it
55
56 } // End of sayHello() method. is using PEAR (http://pear.php.net), so
57 you must have that installed, too. PEAR
58 } // End of HelloWorld class. already comes installed with many all-in-
one WAMP, MAMP, or LAMP stacks; check
your associated documentation if you’re
using one of these. If not, see the sidebar
for some tips on installing PEAR.
For simplicity’s sake, Script 4.8 shows a This will allow you to download the
fully documented HelloWorld.php. latest version of the phpDocumentor
2. Access your computer via the com- directory from that site.
mand-line interface. 4. Install phpDocumentor C:
My assumption is that you already know pear install phpdoc/
how to do this for your platform. If not, phpDocumentor-alpha
search the Web or use my support This instruction comes straight from
forums for answers. the phpDocumentor Web site. It may
change in time; check the site for the
best, current instructions.
146 Chapter 4
Note that on my system, in both Step
Installing PEAR Packages 3 and Step 4, I had to preface these
One PEAR-related thing I do not discuss commands with sudo, to invoke the
in this book is the installation process, for superuser, and include the full path to
two good reasons. First, with the varia- PEAR (both suggestions are made in
tions of available operating systems, it’s the sidebar).
too tough to nail down comprehensive 5. Move to the directory where your PHP
instructions for all potential readers.
scripts are:
Second, experience tells me that many
users are on hosted servers, where they cd /path/to/folder
cannot directly install anything. 6. Document a single file using
Still, installing PEAR is not impossibly
phpdoc -f HelloWorld.php -t docs
hard, and once you master the installa-
tion of a single package, installing more That line tells phpDocumentor to parse
is a snap. If you want to try your hand at the file HelloWorld.php and to write
installing PEAR packages, start by check- the output to the target (-t) directory
ing out the PEAR manual, which has docs, which would be a folder in that
instructions. If you’re still not clear as to same directory. phpDocumentor will
what you should do, search the Web for attempt to create that directory, if it
articles on the subject, particular to your
does not exist.
operating system, and/or post a question
in the book’s supporting forum, where I’ll 7. Open docs/index.html in your
be happy to assist. browser A.
Some installation tips up front:
.. You may need to invoke the For the sake of saving precious book
pear installer as a superuser (or space, the code in this book will not be docu-
using sudo). mented using the full phpDocumentor syntax.
148 Chapter 4
Index
Index 477
B defining in OOP, 121–123
b type specifier, meaning of, 37 deriving from parents, 153–156
backing up database, 356–357 designing with UML, 140–142
backtrace, printing, 50 functions in, 121
behavioral patterns get and set methods, 132
explained, 215 inheriting, 152–156
using, 233 inheriting from, 153–156
books1.xml document, beginning, 413 instanceof keyword, 152
books1.xml file, opening, 416 loosely coupled, 209
bootstrap file methods, 121
confirming module file, 60 in OOP, 120
creating, 57–60 relationship between, 203
header file, 60 switch statement, 123
main page, 57–60 using quotation (“ ) marks with, 152
purpose, 57 variables in, 121
switch conditional, 59–60 ClassName, destructor’s name for, 139
validating, 59 ClassName::methodName() syntax,
explained, 175
browser cache, affecting, 75–79
CLI (command-line interface). See also
interactive PHP CLI
C
backticks, 403
c type specifier, meaning of, 37
built-in Web server, 405–407
cache header types, 75
versus CGI (Common Gateway
cache-control directives, 75 Interface), 378
Cache-Control header type, 75, 79 code blocks, 384–385
caching. See also server caches command-line arguments, 395–399
affecting, 76–79 creating command-line script, 388–390
pages, 75 creating interface, 399
CGI (Common Gateway Interface), versus CLI exec() backtick, 403
(command-line interface), 378
executing bits of code, 383–385
check_urls.php document, creating, 334
fscanf() function for input, 400
class attributes, accessing, 127–132
-h option, 378
class constants versus static attributes, 176
-i option, 378
class design, benefits, 140
-m option, 378
class versus object names, case-sensitivity, 126
pcntl (process control) extension, 403
classes. See also inheritance; OOP (object-
php.ini, 388
oriented programming)
remote server, 384
versus abstract classes, 184
running command-line script, 391–394
attributes in, 121
system() backtick, 403
autoloading, 136
taking user input, 400–404
components, 140
testing installation, 378
creating objects from, 156
using, 378
defining for CMS with OOP example,
-v option, 378
299–303
verifying version of, 381
478 Index
CLI installation testing Color Blue HTML5 design, using, 52
on Mac OS X, 381–382 command-line arguments
on Unix, 381–382 alternative usage, 399
on Windows 7, 379–380 number.php script, 395
client URLs (cURL) utility. See cURL (client using, 396–399
URLs) utility command-line script
_ _clone() method, defining, 197 checking syntax without running, 394
CMS (content management system), 283 creating, 388–390
CMS with OOP example. See also OOP running in Mac OS X, 394
(object-oriented programming) running in Unix, 394
categories table, 286 running in windows, 391–393
comments table, 286 Company.php script, beginning, 208
creating pages, 289 Composite design, creating, 226–230
creating users, 289 Composite pattern
creatorId, 288 considering, 225
database, 286–289 described, 225
defining classes, 299–303 example of, 232
error view file, 297–298 implementing, 225
footer for template, 291–293 subclasses, 226
header file for template, 290 using with Visitor pattern, 232
header for template, 291–293 composite.php script, beginning, 231
home page, 304–307 composition
home page view, 306–307 “has a” relationship, 203
HTML_QuickForm2, 312–319 indicating in UML, 203
MVC (Model-View-Controller) approach, using, 209
284–285
compressing files, 354–362
Page class, 299–301
config.inc.php script, beginning, 45
pages, 284
Config.php script, beginning for Singleton
pages table, 286, 288 class, 217
pages versus posts, 286 configuration file, for modularized site, 45–51
site organization, 285 constants, assigning values to, 176
tags table, 286 _ _construct() method, looking for, 135
template, 290–293 constructors. See also destructors
three-include approach for template, 290 calling directly, 135
User class, 301–303 creating in OOP, 133–135
user type structure, 289 declaring, 135
users, 284 default, 135
users table, 286–287, 289 inheriting, 157–160
utilities file, 294–296 for static members, 178–179
viewing pages, 308–311 subclass, 158–160
code documentation, importance of, 143 syntax, 133
code library, organizing, 208 using, 133–135
collection.dtd document, creating, 422 content management system (CMS). See CMS
collection.xsd document, creating, 428 with OOP example
Index 479
content modules, creating, 61–63 sorting tasks, 16
creational patterns submission conditional, 14
explained, 215 using, 9
using, 225 databases. See also zip codes
cron service backing up, 356–357
adding items to files, 363 distance calculations, 102–107
asterisk (*) parameter, 363 optimizing joins, 103
crontab format, 363 session functions, 84
establishing, 363–365 session handlers, 85–91
establishing for PHP file, 364–365 session table, 82–83
setting ranges with hyphen (-), 363 SHOW WARNINGS command, 99
crontab file, using, 365 storage of session data, 82, 85–87
CRUD functionality, using iCrud interface for, stores table, 100–101
192–193 zip codes, 96–99
cURL (client URLs) utility db_backup.php document, creating, 355
beginning transaction, 345 db_sessions script, beginning, 85
executing transaction, 345 DBG debugging tool, downloading, 454
invoking, 343 debugging tools
POST data, 345 Advanced PHP Debugger, 454
POST method, 345 DBG, 454
redirects, 345 Xdebug, 454
timeout, 345 DECLARE statement, using with variables, 108
using, 343–346 decrypting data with MCrypt, 372–375
cURL library, 344 delimiter, changing for stored functions, 109–110
curl_errno() function, 346 demo document, creating, 137
curl_getinfo() function, 346 design patterns
curl.php script antipatterns, 232
creating, 343 behavioral, 215, 233
running, 351 components, 214
Composite, 225–232
D creational, 215, 225
d type specifier, meaning of, 37 Factory, 220–224
data Gang of Four, 215
decrypting with MCrypt, 372–375 Iterator, 273–277
encrypting with MCrypt, 367–371 Singleton, 216–219
database file, creating for modularized site, 45 Strategy, 233–241
database-driven arrays structural, 215, 225
adding tasks, 10–16 destructors. See also constructors
connecting to database, 10 creating, 136–139
displaying tasks, 16 inheriting, 157–160
HTML form, 13 for static members, 179
retrieving tasks, 14 directories
securing task value, 14 protecting, 70
selecting columns, 8 restricting access, 70
480 Index
displaying results horizontally, 112–117 file functions
display.php script, beginning, 112 fgetc(), 404
distance calculations, performing, 102–107 fgetcsv(), 404
docblocks, using, 144–145 using on STDIN , 404
documentation files, compressing, 354–362
importance of, 143 final definition, using with functions, 163
viewing mistakes, 147 footer.html file, saving, 56
documenting footer.inc.php file, saving, 293
functions, 145 fopen()
methods, 145 versus fsocketopen(), 338
variable declarations, 145 using, 328, 333
DTD, associating with XML file, 419–420 fscanf() function, using, 41, 400
fsocketopen()
E versus fopen(), 338
e type specifier, meaning of, 37 using, 333–338
encapsulation FTP port number, 333
explained, 166 function definitions
use in OOP, 120, 126, 140 anonymous functions, 27–29
encrypting data with MCrypt, 367–371 recursive, 17–24
error handling, purpose of, 460 static variables, 24–26
error view file, creating, 297–298 function parameters
error.html document, beginning, 297 making copies of variables, 30
Exception class, extending, 251–257 passing by reference, 30
exception handling, purpose of, 460 passing by value, 30
exceptions, catching, 244–250, 259–260 type hinting, 15
Expat functions. See also stored functions
functions resource, 439 documenting, 145
parsing XML with, 433 final definition, 163
expat.php document, creating, 434 and references, 30
Expires cache header type, 75, 79
G
F Gang of Four, 215
f type specifier, meaning of, 37 garbage collection, using with session
Factory pattern handlers, 90
versus Abstract Factory, 224 geolocation information, fetching, 340
consequence, 224 get and set methods, using with classes, 132
creating, 220–224 get_quote.php document, creating, 329
described, 220 getter, explained, 171
using, 220
variation, 224 H
factory.php script “has a” relationship, explained, 203
for autoloading classes, 279 header() function, using in caching, 75–77
beginning, 222 header.html file, saving, 55
fetch() method, using, 262 header.inc.php script, using, 291
Index 481
hello_object.php document, creating, processing form data, 315–318
124–126 registerRule(), 315
HelloWorld example validating forms, 314, 322–323
analyzing, 126 validation rules, 314
class documentation, 143–144 HTTP status codes, 334
HelloWorld.php document, creating, 122 httpd.conf file, opening, 68
heredoc syntax
comparing to nowdoc, 36 I
encapsulating strings, 31–36 iCrud interface, declaring, 192–193
EOD delimiter, 32 IMAP port number, 333
EOT delimiter, 32 index page
using, 31–36 confirming module file, 60
Heron’s Formula, using with triangles, 188 creating, 57–60
hinting.php script header file, 60
beginning, 204 main page, 57–60
for Iterator interface, 274 purpose, 57
home page switch conditional, 59–60
creating for CMS with OOP example, validating, 59
304–307 index.html script, beginning, 306
try...catch block, 304 index.php script
view, 306–307 beginning, 57
horizontal results, displaying, 112–117 for home page, 304
.htaccess overrides
inheritance. See also classes; objects; OOP
allowing, 67–69 (object-oriented programming)
AllowOverride directive, 68 attributes, 150
Directory directive, 68 base class, 150
protecting directories, 70, 285 child class, 150–151
HTML tags versus XML tags, 410 derived class, 150
HTML template design, 160
creating, 52–56 indicating in UML, 150
creating pages, 52–56 “is a” relationships, 203
footer file, 56 members of classes, 150
header file, 53–54 methods, 150
HTML_QuickForm2 parent class, 150–151
add a page View file, 324–325 process of, 152
adding pages, 322–325 super class, 150
creating forms, 313, 322–323 terminology, 150
element types, 313 using, 120, 209
filtering form data, 314 inheriting
HTML element types, 313 classes, 152–156
logging out, 320–321 constructors, 157–160
login form, 312 destructors, 157–160
login View file, 318–319 instanceof keyword, using with classes, 152
login.php script, 315–318
482 Index
interactive PHP CLI. See also CLI (command- J
line interface)
joins, optimizing, 103
support for autocompletion, 387
JSON format, using with Web services, 348
using, 386–387
interface keyword, using, 191
L
interface.php script, beginning, 192
lambdas
interfaces
calling, 27
versus abstract classes, 191, 196
downside, 27
associating classes with, 191
using, 27–29
benefit of, 196
Last-Modified cache header type, 75, 78
creating, 191
LDAP port number, 333
defining constructors, 194
load testing, explained, 476
indicating in UML, 196
local variables. See also variables
meanings of, 196
creating for stored function, 110
versus traits, 200
declaring, 108
using, 192–196
login.html script, beginning, 318
IP addresses, unreliability of, 342
login.php script
IP geolocation
creating, 315–318
accuracy, 342
email address, 317
finding user’s location, 339–342
form submission, 317
gethostbyaddr() function, 342
password field, 317
gethostbyname() function, 342
validating form data, 317
MaxMind option, 341
logout.php script, beginning, 320
options, 341
performing, 339–342
M
ip_geo.php script, creating, 339
main.inc.php script, beginning, 61
“is a” relationship, explained, 203
max-age cache-control directive,
iSort interface, implementing, 235–236
meaning of, 75
iSort Strategy pattern, 239–240
MaxMind IP geolocation, features of, 341
iSort.php script, beginning, 235
MCrypt
Iterator design pattern
decrypting data, 372–375
examples in SPL, 273
encrypting data, 367–371
using, 273–277
using with PHP, 366
Iterator interface
member access, controlling, 166–171. See also
current() method, 274
static members
DirectoryIterator, 277
methods
FilterIterator, 277
accessors, 171
implementing, 275–276 constructors, 133–135
key() method, 274, 277
defining in OOP, 121
LimitIterator, 277
documenting, 145
next() method, 274, 277
establishing visibility of, 165
rewind() method, 274, 277
getters, 171
using, 274–277 mutators, 171
valid() method, 274, 277
overriding, 161–164, 173–174
Index 483
mod_rewrite module, 285 MySQL database
allowing .htaccess overrides, 67–69 accessing, 83
enabling URL rewriting, 71–74 calculating distances, 103–107
implementing, 72
using, 67–74 N
Model-View-Controller (MVC), using with CMS namespace class, using, 210–211
and OOP, 284–285 namespace keyword, placement of, 211
modularity, use in OOP, 120 _ _NAMESPACE_ _ constant, 211
modularizing Web sites. See also Web sites namespace.php script, beginning, 210
comments, 48 namespaces
configuration file, 45–51 defining, 207
content modules, 61–63 features of, 207
creating database file, 45 limitations, 207
debugging level, 49 referencing, 208, 211
email address for errors, 48 subnamespaces, 207
error handling, 49–50 using, 208–210
explained, 44 using in multiple files, 211
HTML template, 52–56 networking
index page, 51, 57–60 accessing Web sites, 328–332
printing error and backtrace, 50 classes in PEAR, 332
running script, 48 cURL, 343–346
search module, 64–66 IP geolocation, 339–342
server-side constants, 49 sockets, 333–338
site structure, 50 Web services, 347–351
multidimensional arrays. See also array() Zend Framework classes, 332
function
no-cache directive, meaning of, 75
adding tasks to databases, 10–16
nowdoc syntax, comparing to heredoc, 36
database-driven, 8–10
number format, specifying printing of, 38
defining, 6
number2 script, creating, 396
grade sorting function, 7
number.php script, creating, 389
name-sorting function, 6
printing as defined, 7 O
short array syntax, 2
o type specifier, meaning of, 37
sorting, 4–8, 29
object versus class names, case-sensitivity, 126
for Strategy design, 240
object-oriented programming (OOP). See OOP
two-dimensional, 3–4
(object-oriented programming)
usort() function, 4
objects. See also inheritance
must-revalidate cache-control directive,
cloning, 197
meaning of, 75
copying, 197
mutator, explained, 171
creating from classes, 156
MVC (Model-View-Controller), using with CMS
creating in OOP, 124–126
and OOP, 284–285
serializing, 294
mysql client, SHOW WARNINGS command, 99
use in OOP, 120
484 Index
OOP (object-oriented programming). See also P
classes; CMS with OOP example
Page class
$this attribute, 127–132
creating for CMS with OOP example,
abstract classes, 184–190 299–301
access control, 120, 165–171 getter methods, 300
accessing class attributes, 127–132 page.html script, beginning, 311
attributes versus variables, 121 Page.php script, beginning, 299
autoloading classes, 136 page.php script, beginning, 308
calling object methods, 125 page-viewing page
classes, 120 catching exceptions, 310
composition, 203, 209 Controller, 309
constructors, 133–135 creating, 308–310
controlling member access, 166–171 throwing exceptions, 310
creating objects, 124–126 validating page ID, 310
defining classes, 121–123 page-viewing View, creating, 311
design approaches, 209 parse_url() function
destructors, 136–139 using with sockets, 333–334, 336
encapsulation, 120, 126, 140, 166 validating URLs, 338
inheritance, 120, 150, 209 parsing XML. See also XML (Extensible Markup
installing PEAR packages, 147 Language)
interfaces, 191–196 changing case-folding, 439
methods, 184–190 event-based parser, 432
modularity, 120 with Expat, 433
modularizing application files, 278 with PHP, 434–439
namespaces, 207–211 SimpleXML, 440–446
objects, 120 tree-based parser, 432
overriding, 120 patterns
overriding methods, 161–164 antipatterns, 232
phpDocumentor, 143–147 behavioral, 215, 233
polymorphism, 151 components, 214
recommendation, 160 Composite, 225–232
scope resolution operator (::), 172–175 creational, 215, 225
static members, 176–181 Factory, 220–224
taking actions with data, 120 Gang of Four, 215
theory, 120 Iterator, 273–277
traits, 197–202 Singleton, 216–219
type hinting, 203–206 Strategy, 233–241
visibility, 120, 123, 151 structural, 215, 225
opcode caching, implementing, 473 pcntl (process control) extension, using with
overriden methods, referring to, 173–174 CLI, 403
overriding PDO (PHP Data Objects)
methods, 161–164 calling quote() method, 262
use in OOP, 120 catching exceptions, 259
changing error reporting, 261
Index 485
PDO (continued ) setting up tests, 467–470
connecting to database, 258–259 setUp() method for testing, 467–468, 470
described, 258 Simpletest alternative, 460
executing queries, 261–262 testing Rectangle class, 469
prepared statements, 266–269 $this object, 464
preventing SQL injection attacks, 262 upgrading PEAR, 461
running SELECT queries, 264 phpunit command, executing, 465
SELECT queries, 262–263 polymorphism, use in OOP, 151
using, 260–261 POP port number, 333
PDO object, creating, 260 port numbers for sockets, 333
PEAR (PHP Extension and Application Pragma cache header type, 75
Repository) prepared statements
installing phpDocumentor in, 146 performance benefits, 269
networking classes, 332 try block, 266
upgrading for unit testing, 461 using through PDO, 266–269
PEAR packages, installing, 147 printf() function
percent (% ) sign, using in strings, 41 formats, 37
performance, improving, 473–475 type specifiers, 37
Pet example inheritance design, 160 using, 37–38
pets1.php script printing
beginning, 153 backtrace, 50
for overriding methods, 162 numbers and strings, 38
pets2.php script, for scope resolution operator private cache-control directive, meaning of, 75
(::), 172 profile log, viewing in webgrind, 474–475
PHP, parsing XML with, 434–439 profiling scripts, 471–472
PHP and server proxy server, explained, 75
compressing files, 354–362 proxy-revalidate cache-control directive,
establishing cron, 363–365 meaning of, 75
MCrypt, 366–375 public cache-control directive, meaning of, 75
PHP CLI. See CLI (command-line interface) public variables, accessing, 169. See also
PHP Data Objects (PDO). See PDO (PHP Data variables
Objects)
PHP output, compressing, 362 Q
phpDocumentor queries, executing, 261–262
docblocks, 144–145 query caching, availability of, 473
features, 143–144 query() method, using, 262
installing, 145 query results, displaying horizontally, 112–117
using, 146–147 QuickForm2
PHPUnit. See also unit testing add a page View file, 324–325
creating test cases, 463–465 adding pages, 322–325
defining tests, 462–463 creating forms, 313, 322–323
downloading, 460 element types, 313
installing, 461–462 filtering form data, 314
invoking assertion methods, 464 HTML element types, 313
running tests, 465–466
486 Index
logging out, 320–321 scripts, profiling, 471–472
login form, 312 search module
login View file, 318–319 creating, 64–66
login.php script, 315–318 printing caption, 66
processing form data, 315–318 printing results, 66
registerRule(), 315 search.inc.php script, beginning, 64
validating forms, 314, 322–323 SELECT queries
validation rules, 314 executing, 262–263
quotation (" ) marks, using with classes, 152 populating menu in form, 265
running, 264
R setFetchMode() method, 262
read_mcrypt.php script, beginning, 372 setting fetch mode, 264
Rectangle class try block, 264
constructor added to, 133–135 semicolon (;), use with stored functions, 109
using, 130–132, 201–202 SEO, improving with mod_rewrite, 67–74
Rectangle example, analyzing, 132 serializing objects, 294
Rectangle.php script server
for constructors, 133–135 compressing files, 354–362
creating, 128 establishing cron, 363–365
for tDebug trait, 200 MCrypt, 366–375
recursive functions. See also static variables server caches, implementing, 473.
adding debugging line, 23 See also caching
adding tasks to array, 22 server commands, running, 374
calling, 21–22 service.php script, creating, 349
defining, 18 session data
foreach loop and function, 22 function for destruction of, 89
looping through array, 21 storing as serialized array, 89
nested list of tasks, 19–20 storing in databases, 82, 85–87
using, 17–23 session directory, changing for security, 82
references and functions, 30 session functions, defining, 84
remote server, using with PHP CLI, 384 session handlers
results, displaying horizontally, 112–117 creating, 85–91
RSS feed garbage collection function, 90
Atom offshoot format, 451 using, 91–95
channel content, 447 SessionHandlerInterface class, 270
creating, 447–451 sessions table, creating, 82–83
generating, 448–449 sessions.php script, beginning, 91
rss.php script, beginning, 448 set and get methods, using with classes, 132
set_mcrypt.php script, beginning, 369
S ShapeFactory class, using, 222–224
s type specifier, meaning of, 37 ShapeFactory.php script, beginning for
Factory pattern, 220
scanf() function, using, 41
Shape.php script, beginning, 186
scope resolution operator (::), using,
172–175, 177 short array syntax, using, 2. See also array()
function
Index 487
SHOW WARNINGS command, running, 99 exceptions, 273
Simpletest unit testing Web site, 460 file handling, 271
SimpleXML iterators, 273–277
asXML() method, 446 SplFixedArray, 278
using, 440–446 temporary files, 272
simplexml.php document, creating, 441 using, 270
Singleton class, creating, 217–218 SPL interfaces
Singleton pattern ArrayAccess, 279
Config class, 217–219 Countable, 279
described, 216 SplFileObject, using, 272
implementing, 216 SplTempFileObject, described, 272
UML representation, 216 sprintf() function
sites. See also modularizing Web sites formats, 37
accessing, 328–332 type specifiers, 37
reading with PHP, 329–332 using, 39–41
s-maxage cache-control directive, using with session data, 88
meaning of, 75 SQP injection attacks, preventing, 261–262
SMTP port number, 333 square.php script, creating, 158
sockets SSH port number, 333
connections, 334–335 SSL port number, 333
explained, 333 Standard PHP Library (SPL). See SPL (Standard
fsocketopen(), 333–338 PHP Library)
FTP port, 333 static attributes
GET request, 336 versus class constants, 176
HEAD request, 336 using with static methods, 178–180
HTTP status codes, 334 static members, creating, 178–181. See also
IMAP port, 333 member access
LDAP port, 333 static variables. See also recursive functions;
parse_url() function, 333–334, 336 variables
POP port, 333 versus attributes, 177
ports, 333 using, 24–26
SMTP port, 333 static.php script, beginning, 178
SSH port, 333 stock quotes, retrieving, 329–332
SSL port, 333 stored functions. See also functions
Telnet port, 333 ; (semicolon) in code blocks, 109
Web ports, 333 arguments section, 109
sort.php script changing delimiters, 109–110
for anonymous functions, 28 code section, 109
beginning, 4 creating, 109–111
for static variables, 24 declaring, 108–112
SPL (Standard PHP Library) local variable, 110
autoloading capability, 281 stores table
autoloading classes, 278–280 address selection, 101
data structures, 278 creating, 100–101
populating, 101
488 Index
Strategy design versus interfaces, 200
class definition, 239 precedence, 202
constructor, 237 support for, 197
creating, 235–238 using, 198–199
display() method, 240 triangle
iSort classes, 238–241 calculating area of, 188
iSort interface, 235 setting sides of, 190
multidimensional arrays, 240 Triangle class
sort() method, 237–239 creating, 186–189
Strategy pattern as extension of Shape, 187
described, 233 using, 189–190
example of, 234 Triangle.php script, beginning, 186
using, 233–234 try block
strategy.php script, beginning, 238 using with prepared statements, 266
strings. See also _ _toString() method using with SELECT queries, 264
encapsulating, 31–36 type hinting
percent signs, 41 for arrays, 206
printing, 38 function parameters, 15
structural patterns for functions, 206
explained, 215 for interfaces, 206
using, 225 performing, 203
subclass constructors, creating, 158–160 triggering exceptions, 206
switch statement using, 204–206
using with classes, 123 using in functions, 206
using with index page, 59 type specifiers, 37
T U
tags, HTML versus XML, 410 u type specifier, meaning of, 37
TDD (test-driven development), 461 UML (Unified Modeling Language)
tDebug trait, using, 200 for classes, 140–142
Telnet port number, 333 for composition, 203
temperature script, beginning, 400 for inheritance, 150
$this attribute for interfaces, 196
use in OOP, 127–132 for visibility, 166
using with PHPUnit, 464 UML representation, of Singleton pattern, 216
to-do list, nesting, 9 unit testing. See also PHPUnit
_ _toString() method, defining in classes, assertions, 462
184. See also strings benefits, 460
trait keyword, using, 197 implementing, 460
trait.php script, beginning, 201 TDD (test-driven development), 461
traits Xdebug debugging tool, 465
creating, 197 URL rewriting, enabling, 71–74
incorporating into classes, 202
Index 489
User class W
attributes of, 152 warnings, showing, 99
creating for CMS with OOP example, Web port numbers, 333
301–303
Web services
user input
creating, 347–351
prompting for, 402
JSON format, 348
taking in CLI, 400–404
REST (Representational State Transfer), 347
user-defined functions
returning types of data, 348
anonymous functions, 27–29
stateless, 347
recursive functions, 17–23
technologies related to, 410
static variables, 24–26
using, 342
User.php script, beginning, 301
Web sites. See also modularizing Web sites
usort() function, using, 4
accessing, 328–332
utilities file
reading with PHP, 329–332
catching PDO exceptions, 296
webgrind
database connection, 296
downloading, 471
serialize() function, 294
installing, 471
serializing objects, 294
loading in browser, 474
starting session, 295
using Xdebug with, 471–472
writing, 294–296
viewing profile log in, 474–475
utilities.inc.php script, beginning, 295
write_to_file.php script, opening, 272
V X
variable declaration, documenting, 145
x type specifier, meaning of, 37
variables, passing by reference, 30. See also
Xdebug debugging tool
public variables; static variables
checking code coverage, 465
view_tasks.php script
customizing, 458
beginning, 18
downloading, 454
for caching, 76
ini_set() function, 458
header() function, 76–77
installation requirements, 454
for heredoc syntax, 32
installing on Windows, 455–456
modifying, 33–34
on *nix systems, 454
visibility
profiling in, 471
establishing for methods, 165
using, 457–459
importance of, 166
using with webgrind, 471–472
indicating in UML, 166
XML (Extensible Markup Language). See also
in OOP, 151
parsing XML
private level, 165–166
adding books to file, 414
protected level, 165
& entity, 415
public level, 165
' entity, 415
restriction of, 165
attributes, 415–418
visibility script, beginning, 166
benefit, 424
Visitor pattern, using with Composite, 232
elements, 415–418
vprintf() function, using, 41
entities, 415–418
490 Index
> entity, 415 XSD document
< entity, 415 complex types, 427
modifying, 441 creating attributes, 427
overview, 410–411 defining elements, 426
" entity, 415 incorporating, 425
RSS feed, 447–451 mixed attribute on elements, 431
using formal PHP tags with, 439 simple types, 427
valid, 419 using, 425
well formed, 419 xmlns attribute, 425
writing, 413–414
XML document, 413 Z
XML Schemas Zend Framework, network-related classes, 332
defining, 419–431 zip codes. See also databases
defining attributes, 421–422 database, 96–99
defining elements, 420–421 importing data, 98
<!DOCTYPE rootelement, 419 tables, 96
element attribute types, 421 zlib
element type symbols, 421 a+ mode, 355
element types, 420–421 b mode, 355
incorporating DTD, 419–420 compressed binary files, 362
incorporating XSD, 425 compressing files with, 354–362
using, 425 f mode, 355
writing Document Type Definition, 422–424 file open modes, 355
XML syntax h mode, 355
comments, 413 a mode, 355
data, 412 r mode, 355
prolog, 412 r+ mode, 355
rules for elements, 412 verifying support for, 354
white space, 413 w mode, 355
XML tags versus HTML tags, 410 w+ mode, 355
XML version, indicating, 412 x mode, 355
ZIP archives, 362
Index 491