OBJEC T-ORIE NT E D
PHP
OBJEC T-ORIE NT E D
PHP
C O N C E P T S , T E C H N I Q U E S , A N D C O D E
P E T E R L A V I N
®
Trying to learn the concepts of object-oriented
programming using a language like C++ can be an
intimidating experience. The simpler object model of
PHP makes it the ideal language for an introduction to
object-oriented programming.
For the uninitiated, this guide to the latest version of
PHP offers a speedy introduction to object-oriented
programming, including a thorough explanantion of
class as well as coverage of constructors, destructors,
inheritance, polymorphism and interfaces. In this easy
to follow guide, the author teaches by example, and
couples new concepts with snippets of example code
(which are available for download from the book’s
companion website).
With Object-Oriented PHP, you’ll learn to:
• Promote code reuse by creating your own classes
and using built-in classes
• Customize and improve classes through inheritance
• Simplify database access by developing MySQL
database and result set classes
• Incorporate an RSS reader into your site using only
four lines of code
• Use XML easily with an object-oriented approach
• Employ PHP to autogenerate documentation for
your code
• Make thumbnail images on the fly
• Replace clumsy error trapping with Exception
handling
• Take full advantage of advanced OO features in PHP
Object-Oriented PHP will show you how to maximize
PHP’s features, with much less work than you might think.
With Object-Oriented PHP, you can master the basics of
OOP and get up to speed on PHP in one fell swoop.
A B O U T T H E A U T H O R
Peter Lavin runs a web development firm based in
Toronto, Canada, and he writes regularly on all things
tech. He has been published in a number of magazines
and online publications, including UnixReview.com,
Spider Magazine and PlugIn Magazine. He is also a
contributor to the forthcoming PHP Hacks (O’Reilly).
ww w.nostarch.com
“I L AY F L AT.”
This book uses RepKover —a durable binding that won’t snap shut.
TH E FI NE ST I N G E E K E N T E RTA I NM E NT
™
SHELVE IN:
WEB PROGRAMMING
$39.95 ($51.95 CDN)
®
L E A R N T H E
B A S I C S O F
O B J E C T - O R I E N T E D
P R O G R A M M I N G
A N D P H P
L E A R N T H E
B A S I C S O F
O B J E C T - O R I E N T E D
P R O G R A M M I N G
A N D P H P
®
O B J E C T- O R I E N T E D P H P
O B J E C T- O R I E N T E D P H P
L A V I N
OOPHP_02.book Page ii Friday, May 5, 2006 2:25 PM
OBJECT-ORIENTED
PHP
Concepts, Techniques,
and Code
by Peter Lavin
San Francisco
®
OOPHP_02.book Page iii Friday, May 5, 2006 2:25 PM
OBJECT-ORIENTED PHP. Copyright © 2006 by Peter Lavin.
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or
mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior
written permission of the copyright owner and the publisher.
Printed on recycled paper in the United States of America
1 2 3 4 5 6 7 8 9 10 – 09 08 07 06
No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and
company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark
symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the
benefit of the trademark owner, with no intention of infringement of the trademark.
Publisher: William Pollock
Managing Editor: Elizabeth Campbell
Associate Production Editor: Christina Samuell
Cover and Interior Design: Octopod Studios
Developmental Editor: William Pollock
Technical Reviewer: Peter MacIntyre
Copyeditors: Publication Services, Inc. and Sarah Lemaire
Compositor: Riley Hoffman
Proofreader: Stephanie Provines
For information on book distributors or translations, please contact No Starch Press, Inc. directly:
No Starch Press, Inc.
555 De Haro Street, Suite 250, San Francisco, CA 94107
phone: 415.863.9900; fax: 415.863.9950; ; www.nostarch.com
The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been
taken in the preparation of this work, neither the author nor No Starch Press, Inc. 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
information contained in it.
Library of Congress Cataloging-in-Publication Data
Lavin, Peter.
Object-oriented PHP : concepts, techniques, and code / Peter Lavin.
p. cm.
Includes index.
ISBN 1-59327-077-1
1. PHP (Computer program language) 2. Object-oriented programming (Computer science) I. Title.
QA76.73.P224L38 2006
005.1'17 dc22
2006015309
oophp_TITLE_COPY.fm Page iv Tuesday, May 16, 2006 9:32 AM
BRIEF CONTENTS
Acknowledgments xiii
Introduction xv
Chapter 1: What a Tangled Web We Weave 1
Chapter 2: Basics of Object-Oriented Programming 5
Chapter 3: Object-Oriented Features New to PHP 5 11
Chapter 4: Show a Little Class 17
Chapter 5: Mod UR Class 25
Chapter 6: The ThumbnailImage Class 35
Chapter 7: Building the PageNavigator Class 47
Chapter 8: Using the PageNavigator Class 57
Chapter 9: Database Classes 65
Chapter 10: Improvement Through Inheritance 75
Chapter 11: Advanced Object-Oriented Programming Concepts 91
Chapter 12: Keeping It Fresh 99
Chapter 13: More Magic Methods 111
Chapter 14: Creating Documentation Using the Reflection Classes 125
Chapter 15: Extending SQLite 139
Chapter 16: Using PDO 157
Appendix A: Setting Up PHP 5 165
Appendix B: Conversion Table: PHP 4 and PHP 5 169
Glossary 173
Index 179
OOPHP_02.book Page v Friday, May 5, 2006 2:25 PM
OOPHP_02.book Page vi Friday, May 5, 2006 2:25 PM
CONTENTS IN DETAIL
ACKNOWLEDGMENTS xiii
INTRODUCTION xv
What Does This Book Have to Offer? xvi
Who Should Read This Book? xvi
Requirements xvi
Software xvi
Skills xvii
Overview of Contents xvii
Companion Website xix
Resources xx
Websites xx
Books xx
1
WHAT A TANGLED WEB WE WEAVE 1
Do We Really Need Objects? 2
Just a Scripting Language 2
Object Orientation Is for Large Software Shops 3
Leave Well Enough Alone 3
Increased Complexity 3
The PHP Culture 4
2
BASICS OF OBJECT-ORIENTED PROGRAMMING 5
Class 6
Classes Versus Records 6
A Cohesive Whole 6
Objects Are Instances 6
Objects Need Access Modifiers 7
Object Reuse and Inheritance 7
Multiple Inheritance 8
Having Your Cake and Eating It Too 8
Where to Go from Here 9
3
OBJECT-ORIENTED FEATURES NEW TO PHP 5 11
Access Modifiers 12
Built-in Classes 12
Exceptions 12
Database Classes 13
OOPHP_02.book Page vii Friday, May 5, 2006 2:25 PM
viii Contents in Detail
Web Services 13
Reflection Classes 14
Iterator 14
Backward Compatibility 14
Pass By Reference 14
Prognosis 15
Where to Go from Here 15
Adoption of PHP 5 16
Compromise 16
4
SHOW A LITTLE CLASS 17
Design 18
Defining the Problem 18
Not the Da Vinci Code 19
The Constructor 19
Referencing Instance Variables 20
Wrapper Methods 20
Creating an Instance 21
What Have You Accomplished? 23
But Will It Fly? 23
5
MOD UR CLASS 25
Upgrading to PHP 5 26
Access Modifiers 26
The Constructor 28
Modifying Your Class 29
Reconstructing the Constructor 29
Filtering Content 31
Resetting the Array 32
Summary of Changes 33
6
THE THUMBNAILIMAGE CLASS 35
What Does a Designer Do? 36
Mimicking the Designer 36
Help from PHP Functions 36
The ThumbnailImage Class 37
Data Members 37
Deconstructing the Constructor 37
Two Ways to Construct an Object 38
Internal Behavior—Private Methods 39
Must It Be Private? 40
A Helper Method 40
Public Methods 41
Garbage Collection 41
OOPHP_02.book Page viii Friday, May 5, 2006 2:25 PM
Contents in Detail ix
Displaying the Image 41
Get and Set Methods 42
Image Quality 42
When to Change the Quality 43
Displaying a Thumbnail 44
Putting It All Together 44
Where to Go from Here 45
7
BUILDING THE PAGENAVIGATOR CLASS 47
How Will the Navigator Behave? 47
Different Kinds of Searches 48
What Will It Look Like? 48
The Code 49
The Constructor 51
Ain’t Misbehavin’ 52
Other Constructor Method Calls 52
The getNavigator Method 54
Move First and Move Previous 54
Main Body of the Navigator 55
Move Next and Move Last 56
Current and Total Number of Pages 56
Where to Go from Here 56
8
USING THE PAGENAVIGATOR CLASS 57
DirectoryItems Change 58
CSS and Reusability 58
Paging with Class 60
Displaying an Array Slice 61
Creating the PageNavigator Object 62
Where to Go from Here 63
9
DATABASE CLASSES 65
Using What You Know 65
One Lump or Two? 66
The MySQLConnect Class 66
A Class-Conscious Variable 67
Making Other Connections 68
You Can Only Get There from Here 68
The MySQLResultSet Class 69
Using the Page Navigator 70
Ordering, Filtering, and Extracting 71
Traversing the Result Set 72
Your Navigator Needs Directions 73
Where to Go After the Navigator 74
OOPHP_02.book Page ix Friday, May 5, 2006 2:25 PM
x Contents in Detail
10
IMPROVEMENT THROUGH INHERITANCE 75
The Standard PHP Library 76
Extending a Class Through Inheritance 76
The Exception Class 77
protected 77
final 78
More Magic Methods 78
Replacing Errors with Exceptions 79
The MySQLException Class 80
Changes to the MySQLConnect Class 81
Prodding Your Class into Action 82
Catching Exceptions 83
Implementing an Interface 84
Learning About the Iterator Interface 85
Implementation 86
Leaving a Method Undefined 88
Implementation and Access 88
Iterating Through a MySQLResultSet 89
Where to Go from Here 89
11
ADVANCED OBJECT-ORIENTED PROGRAMMING
CONCEPTS 91
Abstract Classes 91
Private Methods Can’t Be Abstract 92
Interface or Pure Abstract Class? 92
Polymorphism 93
Controlling How Functions Are Used 93
Static Classes 94
Static Math Classes 94
Instances of Static Classes 95
Preventing Instantiation of a Static Class 96
Design Patterns 96
The Singleton Pattern 96
Which Implementation? 98
Where to Go from Here 98
12
KEEPING IT FRESH 99
SimpleXML 100
XML 100
RSS 101
Structure of an RSS File 101
Reading the Feed 102
Site-Specific Search 103
Google API 104
AJAX 104
Installing SOAP 104
OOPHP_02.book Page x Friday, May 5, 2006 2:25 PM