Thematerial in the first half of this book covers vital components ofeveryday web programming: object-oriented programming,MySQL, SQLite, and XML.. Selling or distributing a CD-ROM of ex
Trang 2covers more advanced features and provides hands-on experienced through short, sample programs included throughout.
Trang 7Printed in the United States of America
Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472
O'Reilly books may be purchased for educational, business, orsales promotional use Online editions are also available for
most titles (http://safari.oreilly.com) For more information,contact our corporate/institutional sales department: (800)
998-9938 or corporate@oreilly.com
Nutshell Handbook, the Nutshell Handbook logo, and the
O'Reilly logo are registered trademarks of O'Reilly Media, Inc.Upgrading to PHP 5, the image of Galapagos tortoises, and
related trade dress are trademarks of O'Reilly Media, Inc
Many of the designations used by manufacturers and sellers todistinguish their products are claimed as trademarks Wherethose designations appear in this book, and O'Reilly Media, Inc.was aware of a trademark claim, the designations have beenprinted in caps or initial caps
While every precaution has been taken in the preparation of thisbook, the publisher and author assume no responsibility for
errors or omissions, or for damages resulting from the use ofthe information contained herein
Trang 8PHP is a powerful yet easy-to-use tool for creating dynamic webcontent The perfect language for projects great and small, PHP
is used by Yahoo!, millions of personal home pages, and
everything in-between Best of all, PHP is open source and runs
on Unix, Windows, and Mac OS X
oriented programming, an integrated suite of XML tools, an all-new MySQL extension, web services with SOAP and REST, andhundreds of other improvements
The latest version, PHP 5, contains robust support for object-There are so many updates and new features, it's difficult to get
a handle on all the changes Documentation is scarce,
scattered, and rarely in-depth This book steadily guides youfrom the world of PHP 4 to PHP 5, covering what's completelynew, what's received an overhaul, and what's just slightly
different enough to slip you up
Trang 9perfectly under PHP 5 That's why Upgrading to PHP 5 provides you with detailed side-by-side comparisons of PHP 4 and PHP 5
Finally, it provides an address book program This concrete
example combines the new features of PHP 5, demonstratingtheir usefulness in the context of a complete application Theaddress book shows you exactly how PHP 5 makes it faster andeasier to develop more powerful and flexible web applications
Trang 10This book is not for people new to PHP If you're looking to learnthe language, check out these three excellent alternatives:
1 Learning PHP 5, by David Sklar This book provides a
gentle introduction to PHP for web designers and
other nontechnical people familiar with HTML and the Web, but not with programming and databases.
Programming PHP, by Rasmus Lerdorf and Kevin Tatroe Co-authored by the creator of PHP, Programming PHP is aimed at
anyone looking to learn PHP An exhaustive reference, this bookcovers all aspects of PHP, from basic concepts to advanced
techniques
Web Database Applications with PHP and MySQL, by Hugh
E.Williams and David Lane If you're comfortable programmingbut have only just started using SQL, this book teaches you
Trang 11This book is divided into 10 chapters and 3 appendixes Thematerial in the first half of this book covers vital components ofeveryday web programming: object-oriented programming,MySQL, SQLite, and XML It's hard to use PHP 5 without them.Specifically:
extensions are all extremely useful for solving specific tasks.The more you program in PHP 5, the more you'll find yourselfintegrating these features into your code
Chapter 6, Iterators and SPL, shows how iterators and SPL
let you loop through directories, database queries, and XMLdocuments
Trang 12to integrate PHP 5 into your existing web server and PHP 4setup
Trang 13The official PHP Manual contains thousands of pages
covering all aspects of PHP It's an invaluable resource forlooking up functions
PHP mailing lists (http://www.php.net/mailing-lists.php)
Discuss PHP on the PHP mailing lists Don't be shy, there's alist for every topic: programming, databases, and even
Trang 14PEAR (http://pear.php.net/)
Don't reimplement the wheel, download it from PEAR
PEARthe PHP Extension and Application RepositorycontainsPHP classes that simplify forms processing, provide a
database abstraction layer, generate class documentation,and solve hundreds of other tasks
PECL (http://pecl.php.net/)
PECL is PEAR's sister PECLthe PHP Extension CommunityLibraryis a collection of PHP extensions written in C They'rejust like the bundled PHP extensions, except they're
Trang 15These books are all helpful problem-solving guides and
references Most of the books in the list are web-specific, andthe top six books are my favorite PHP and MySQL texts
Trang 16The following programming and typesetting conventions areused in this book
Programming Conventions
The <?php and ?> opening and closing markers that begin andend a PHP program are generally omitted from examples in thisbook, except in examples where the body of the code includes
an opening or closing marker
The examples in this book were written to run under PHP 5 onboth Unix and Windows, except where noted in the text
At the time this book went to press, the latest available version
of PHP 5 was Release Candidate 3 (RC3) Also, MySQL 4.1 was
in beta It is possible that some changes may occur betweenRC3 and the final release Please check the online errata at
http://www.oreilly.com/catalog/upgradephp5/errata/ for anylast-minute updates
Typesetting Conventions
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, fileextensions, pathnames, and directories
Trang 17Indicates commands, options, switches, variables,
attributes, keys, functions, types, classes, namespaces,methods, modules, properties, parameters, values, objects,events, event handlers, XML tags, HTML tags, macros, thecontents of files, or the output from commands
Trang 18This book is here to help you get your job done In general, youmay use the code in this book in your programs and
documentation You do not need to contact us for permissionunless you're reproducing a significant portion of the code Forexample, writing a program that uses several chunks of codefrom this book does not require permission Selling or
distributing a CD-ROM of examples from O'Reilly books does
require permission Answering a question by citing this bookand quoting example code does not require permission
Incorporating a significant amount of example code from this
book into your product's documentation does require
permission
We appreciate, but do not require, attribution An attributionusually includes the title, author, publisher, and ISBN For
example: "Upgrading to PHP 5, by Adam Trachtenberg.
Copyright 2004 O'Reilly Media, Inc., 0-596-00636-5."
If you feel your use of code examples falls outside fair use orthe permission given here, feel free to contact us at
permissions@oreilly.com
Trang 19Please address comments and questions concerning this book tothe publisher:
http://www.oreilly.com/catalog/upgradephp5/
To comment or ask technical questions about this book, sendemail to:
bookquestions@oreilly.com
For more information about our books, conferences, ResourceCenters, and the O'Reilly Network, see our web site at:
http://www.oreilly.com/
Trang 20there's not a bozo in the bunch.
Trang 21Genevieve d'Entremont prepared this book for productionand repaired my prose
chromatic published my PHP articles on ONLamp.com
A cornered Andy Oram and Bruce Epstein graciously
provided editorial guidance and support one late night atFOO Camp
Rob Romano transformed my crayon sketches into works ofart
Betsy Waliszewski got the word out early and often
However, two people contributed more messages to my inboxthan the others combined: Tatiana Diaz and Nat Torkington
I have no idea how Tatiana Diaz put up with my all-too-oftenclaims of "Oh sure, I can make that deadline," without reachingthrough the Internet and strangling me Without her gentle
prodding, Upgrading to PHP 5 wouldn't be available until PHP 6.
Nat Torkington is a great editor He gave me a push when I gotstuck and helped me reframe chapters when they became
misaligned He even lets me make Perl 6 jokes at his expense Ipay him the greatest compliment I can: this book would be farless helpful without him
Thanks to my family and friends for their support and
encouragement
Extra special thanks go to Elizabeth Hondl, my beautiful
princess and talking frog
Trang 22PHP 4 is a wildly popular web programming language Web
servers on over 15,000,000 domains support PHP PHP is themost popular Apache module by almost a 2-to-1 margin But ifPHP's so great, why do we need PHP 5?
Well, PHP 4 isn't perfect While it makes developing web
applications quick and easy, it's occasionally weighted down byits legacy baggage This makes tackling some problems
MySQL
XML
These items have all been completely rewritten, turning themfrom limitations into star attractions While these changes alonewarrant a new version of PHP, PHP 5 also provides:
SQLite for an embedded database
Iterators
Trang 23Streams
SOAP
Some of these features, such as iterators and exceptions, areavailable only due to fundamental changes in PHP's core
Others, such as streams and SQLite, are PHP 4.3 features thathave matured into prime-time use in PHP 5
This book shows you how to take advantage of these new
features in your applications Additionally, it places a specialemphasis on not just telling you what's new, but showing youhow and why it's new
Whenever possible, there's a direct comparison between thePHP 4 method of solving a task and the PHP 5 solution The PHP
5 way is frequently shorter, more elegant, and provides youwith greater flexibility The before-and-after examples
demonstrate in clear code what's better about PHP 5 and
provide you with concrete examples to ease the transition fromPHP 4 to PHP 5
This chapter serves as a dual introduction to both PHP 5 and
Upgrading to PHP 5 It begins with a brief history of PHP that
provides the motivation behind PHP 5 The next section
provides a short description of all the major new features ofPHP 5 and, at the same time, explains how the book is
organized This chapter ends with a discussion of how to installand configure PHP 5
Trang 24To understand why PHP 5 came to exist, it's necessary to
quickly review the evolution of PHP as a language
When Rasmus Lerdorf created PHP back in 1995, it wasn't evencalled PHPhis Personal Home Page/Forms Interpreter languagewas known as PHP/FI At the time, PHP/FI's main focus wassolving small-time web tasks: guest books, hit counters, andbasic forms processing Its major benefit was its simplicity;PHP/FI made it easy to handle all the messy tasks thrown at aweb developer Additionally, it's C-like syntax was already
understood by many programmers
Over the next two years, PHP/FI gradually grew in popularity.However, by 1997, PHP/FI was already showing its age As theInternet gathered steam, programmers began to create morecomplex applications, such as e-commerce shopping carts
PHP/FI's quirks and limitations hindered development It wastoo slow and was missing some basic features, such as for andforeach loops
These problems caused Zeev Suraski and Andi Gutmans, ofZend fame, to begin work on a new version of PHP/FI This
version, which became PHP 3, solved many difficulties faced byPHP/FI developers while remaining true to the essential nature
of PHP/FI
In particular, PHP 3 was faster and more efficient than PHP/FI.The new parser also provided the opportunity to iron out somelanguage oddities, making PHP more consistent PHP 3's othermajor advance was an easy-to-use extension API Developersfrom all over contributed extensions to PHP, effectively turningPHP from a programming language into an entire web
development environment
Trang 25introduced a very simplistic object-oriented syntax Originallythe result of a weekend hack, developers flocked to objects,much to the surprise of Zeev and Andi Unfortunately, PHP 3was ill-equipped to provide all the object-oriented features
While PHP 4 provided yet another burst of power, its secondaryobjective was backward compatibility There was a strong
emphasis on not breaking PHP 3 scripts under PHP 4 As a
result, beefing up the core language was not a main focus ofPHP 4 PHP 4 was released in May 2000, almost two years afterPHP 3
A lot has happened over the last four years Perl may be the
"duct tape of the Internet," but PHP is the real glue that holdsthe Web together However, PHP still faces challenges The
problems of performance and flexibility have long been
conquered, but now PHP is under attack from the twin foes ofJava and C#
Over the past 10 years, Java and C# have introduced advancedobject-oriented programming concepts to web development Yet
in many ways, despite all the improvements, PHP 4.3 is still thesame procedural language that Rasmus wrote a decade ago.PHP 5 finally grants developers their wish, providing a full set ofobject-oriented features
These features, which are discussed in Chapter 2, allow
developers to more easily develop large-scale applications
without resorting to the cumbersome workarounds necessary inPHP 4 They also let you write cleaner code that's less error-
Trang 26prone and more maintainable.
Trang 27Better object-oriented features aren't the only new features ofPHP 5 Many extensions have been rewritten to take advantage
of PHP 5's new capabilities, and many new extensions have
been added to the distribution
1.2.1 MySQL
The MySQL database is PHP's partner in crime Many developerspower their web sites with MySQL, yet PHP's original MySQLextension dates back to the days of PHP/FI It's showing its
age
In retrospect, some design decisions for the MySQL extensionweren't the best solution after all Also, the latest versions ofMySQL, 4.1 and 5.0, introduce many new features, some ofwhich require significant changes to the extension
As a result, PHP 5 comes with a completely new and improvedMySQL extension Dubbed MySQLi, for the MySQL Improvedextension, MySQLi offers prepared statements, bound
parameters, and SSL connections It even takes advantage ofPHP 5's new object-oriented support to provide an OO interface
Trang 28supports transactions, subqueries, triggers, and many otheradvanced database features
Like MySQLi, SQLite also comes with dual procedural and OOinterfaces
1.2.3 XML
XML is a key part of web development, so PHP 5 offers a fullselection of new XML tools A major goal of XML in PHP 5 is
interoperability among each of the different XML extensions,making them a unified unit instead of individual agents
The new Document Object Model (DOM) extension is leaps andbounds better than PHP 4's experimental version It also usesnew PHP 5 features to comply with the DOM specification,
fulfilling the goal of DOM as a language-neutral API for XML
There's also a new Extensible Stylesheet Language
Transformations (XSLT) extension that operates on XML
documents and DOM objects You can transform DOM objectsusing XSLT and receive translated documents from XSLT Youcan even pass XML nodes back and forth between XSLT and PHPfrom within a stylesheet
Perhaps the most innovative part of PHP 5 is the SimpleXMLextension This lightweight interface to XML lets you easily
iterate through XML documents without the overhead of DOM orthe oddness of XSLT It's perfect for documents where you knowthe specification and want to quickly extract data
Chapter 5 covers all these topics, plus the original Simple APIfor XML (SAX) extension and an XPath extension, used for
Trang 291.2.6 Streams, Filters, and Wrappers
Trang 30writing data using protocol-specific objects known as wrappers.Streams also let you modify the data flowing through them byattaching filters
First introduced in PHP 4.3, streams are an underutilized part ofPHP PHP 5 expands upon the existing streams infrastructure toallow more extensive wrappers, and to let you create filters
directly in PHP instead of in C
Chapter 8 demonstrates how to create a shared memory
wrapper and two streams, one for encoding HTML entities andanother for decoding them
1.2.7 Other Extensions
Chapter 9 covers three new pieces of PHP 5: SOAP, Tidy, andthe Reflection classes
SOAP is a key component of the fast-growing web services field.This extension lets developers create SOAP clients with or
without a Web Services Description Language (WSDL) file, andalso implement SOAP servers in PHP
The Tidy extension makes it easy to ensure that your output isvalid HTML and XHTML Its smart parser brings even the mostunruly of files into compliance with the latest W3C
specifications
Nothing less than complete code introspection is the goal of theReflection classes This set of classes lets you examine classes,methods, parameters, and more, to discover object attributes
It is now simple and easy to create PHP class browsers,
debuggers, and other tools that rely on gathering details aboutobjects and functions
Trang 31This address book lets you add contact information and searchstored records using both a web and command-line interface.The output is completely separated from application logic, andthe program uses a simple series of template classes to controlits formatting
in many ways, it's easiest to be tripped up by minor changes.You know you're on new ground with the mysqli extension, but,unless you read Appendix B, you probably would not know thatyou can now pass optional parameters by reference, or thatstrrpos( ) behaves slightly differently than before, or eventhat the command-line version of PHP has the ability to execute
Trang 32code on every line of input.
Trang 33You can download PHP 5 from
http://www.php.net/downloads.php The installation process isidentical to PHP 4; however, PHP 5 does have some new
configuration options See Table C-1 in Appendix C for a
complete list
During the transition from PHP 4 to PHP 5, it's common to want
to run both versions of PHP simultaneously This lets you easilytest code under PHP 5 without switching completely away fromPHP 4 It also allows you to slowly migrate scripts from PHP 4 toPHP 5, as you can control which version of PHP parses specificsets of pages
One option is to run two separate web servers, either on
different machines or on different ports on the same machine.The primary advantage of using two web servers is that you canrun both PHP 4 and PHP 5 as a module The disadvantages arethat you either need multiple computers at your disposal or
need to be familiar with installing Apache (or your particularweb server of choice) It's also a lot of work for a temporarysituation
Another solution is to continue using your existing web serverand install one version of PHP as a module and another as aCGI This gets you up and running with both versions with
minimal fuss; however, the CGI version of PHP lacks certainfeatures included in the Apache module
Appendix C provides detailed instructions for setting up PHP 4and PHP 5 under Apache on both Unix and Windows It showshow to configure Apache to switch between the versions both
on a directory-by-directory basis and by setting up a virtual
server on another port
Trang 34This chapter introduces object-oriented programming (OOP)and explains all the object-oriented (OO) features in PHP 5 Thechapter assumes no prior knowledge of OOP, so if this is yourfirst time learning it, that's okay
chapter shows you how and why you should modify your
existing code to take full advantage of PHP 5
Early versions of PHP were strictly procedural: you could definefunctions, but not objects PHP 3 introduced an extremely
rudimentary form of objects, written as a late-night hack Back
in 1997, nobody expected the explosion in the number of PHPprogrammers, nor that people would write large-scale programs
in PHP Therefore, these limitations weren't considered a
problem
Over the years, PHP gained additional object-oriented features;however, the development team never redesigned the core OOcode to gracefully handle objects and classes As a result,
although PHP 4 improved overall performance, writing complex
OO programs with it is still difficult, if not nearly impossible
PHP 5 fixes these problems by using Zend Engine 2 The firstversion of the Zend Engine was written for PHP 4 to handle
PHP's core functionality, such as what type of objects you canuse, and to define the language's syntax
Trang 35If you don't have experience with object-oriented programmingoutside of PHP, then you're in for a bit of a surprise While some
of the new features allow you to do things more easily, manyfeatures don't let you do anything new at all In many ways,
they restrict what you can do.
Even though it seems counterintuitive, these limitations actuallyhelp you quickly write safe code because they promote codereuse and data encapsulation These key OO programming
concepts are explained throughout the chapter
Trang 36accesses the table whenever it needs to fetch a person's emailaddress:
Trang 38outside access This prevents people from relying on code thatmay change and forces them to use your functions to reach the
data Functions of this type are known as accessors, because
they allow access to otherwise protected information Whenredesigning code, if you update the accessors to work as
of data
Trang 39Convert a class into an object by using the new keyword:
$rasmus = new Person;
This command causes PHP to look for a class labeled as Person,create a new copy, and assign it to $rasmus This process is
known as instantiating an object or creating a new instance of a
class
For now, don't worry about the actual syntax for defining
Person Also, it's not necessary to know how Person storesdata This information is encapsulated away, and you're forced
to invoke the setName( ) function on that specific instance ofthe class
Trang 40author agrees that as long as a person uses accessor methods,such as setName( ) and getName( ), they'll always work, even
if the author redesigns the class
The full details on class creation come later, but here's a firstlook at the elements of a simple class For example, the Personclass can look like this: