SlideShare ist ein Scribd-Unternehmen logo
1 von 720
Downloaden Sie, um offline zu lesen
Gutmans_Frontmatter Page i Thursday, September 23, 2004 9:05 AM




                          PHP 5 Power Programming
Gutmans_Frontmatter Page ii 1 Wednesday, September 15, 9:05 AM
perens_series_7x9.25.fm Page Thursday, September 23, 20042004 10:54 AM




                            BRUCE PERENS’ OPEN SOURCE SERIES
                                                 http://www.phptr.com/perens




               ◆ Java Application Development on Linux
                          Carl Albing and Michael Schwarz

               ◆ C++ GUI Programming with Qt 3
                          Jasmin Blanchette, Mark Summerfield

               ◆ Managing Linux Systems with Webmin: System Administration and
                   Module Development
                      Jamie Cameron

               ◆ Understanding the Linux Virtual Memory Manager
                          Mel Gorman

               ◆ Implementing CIFS: The Common Internet File System
                          Christopher Hertel

               ◆ Embedded Software Development with eCos
                          Anthony Massa

               ◆ Rapid Application Development with Mozilla
                          Nigel McFarlane

               ◆ The Linux Development Platform: Configuring, Using, and Maintaining a
                   Complete Programming Environment
                      Rafeeq Ur Rehman, Christopher Paul

               ◆ Intrusion Detection with SNORT: Advanced IDS Techniques Using SNORT,
                   Apache, MySQL, PHP, and ACID
                      Rafeeq Ur Rehman

               ◆ The Official Samba-3 HOWTO and Reference Guide
                           John H. Terpstra, Jelmer R. Vernooij, Editors

               ◆ Samba-3 by Example: Practical Exercises to Successful Deployment
                          John H. Terpstra
Gutmans_Frontmatter Page iii Thursday, September 23, 2004 9:05 AM




                          PHP 5 Power Programming




                             Andi Gutmans, Stig Sæther Bakken,
                                    and Derick Rethans




                                                           PRENTICE HALL
                                                           Professional Technical Reference
                                                           Indianapolis, IN 46240
                                                           www.phptr.com
Gutmans_Frontmatter Page iv Thursday, September 23, 2004 2:14 PM




       The authors and publisher have taken care in the preparation of this book, but make no expressed or implied
       warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for inciden-
       tal or consequential damages in connection with or arising out of the use of the information or programs con-
       tained herein.

       Publisher: John Wait
       Editor in Chief: Don O’Hagan
       Acquisitions Editor: Mark L. Taub
       Editorial Assistant: Noreen Regina
       Development Editor:Janet Valade
       Marketing Manager: Robin O'Brien
       Cover Designer: Nina Scuderi
       Managing Editor: Gina Kanouse
       Senior Project Editor: Kristy Hart
       Copy Editor: Specialized Composition
       Indexer: Lisa Stumpf
       Senior Compositor: Gloria Schurick
       Manufacturing Buyer: Dan Uhrig

       The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special
       sales, which may include electronic versions and/or custom covers and content particular to your business,
       training goals, marketing focus, and branding interests. For more information, please contact:
                 U. S. Corporate and Government Sales
                 (800) 382-3419
                 corpsales@pearsontechgroup.com
       For sales outside the U. S., please contact:
                 International Sales
                 international@pearsoned.com
       Visit us on the Web: www.phptr.com

       Library of Congress Cataloging-in-Publication Data:
       2004107331
       Copyright © 2005 Pearson Education, Inc.
       This material may be distrubuted only subject to the terms and conditions set forth in the Open Publication
       License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/).

               Pearson Education, Inc.
               One Lake Street
               Upper Saddle River, NJ 07458

       Every effort was made to contact and credit all copyright holders. Use of material without proper credit
       is unintentional.

       ISBN 0-131-47149-X
       Text printed in the United States on recycled paper at Phoenix in Hagerstown, Maryland.
       First printing, [October 2004]
Gutmans_Frontmatter Page v Thursday, September 23, 2004 9:05 AM




             To Ifat, my wife and best friend, who has patiently put up with my
              involement in PHP from the very beginning, and has encouraged
                          and supported me every step of the way.
                                        Andi Gutmans


                              To Marianne, for patience and encouragement.
                                          Stig Sæther Bakken


                    To my parents, who care for me even when I’m not around;
                                   and to 42, the answer to life,
                                    the universe of everything.
                                         Derick Rethans
Gutmans_Frontmatter Page vi Thursday, September 23, 2004 9:05 AM
Gutmans_Frontmatter Page vii Thursday, September 23, 2004 9:05 AM




                                                                                               vii




           Contents
                              Foreword by Zeev Suraski

                              Preface: Introduction and Background

                              Chapter 1:           What Is New in PHP 5?
                              Chapter 2:           PHP 5 Basic Language
                              Chapter 3:           PHP 5 OO Language
                              Chapter 4:           PHP 5 Advanced OOP and Design Patterns
                              Chapter 5:           How to Write a Web Application with PHP
                              Chapter 6:           Databases with PHP 5
                              Chapter 7:           Error Handling
                              Chapter 8:           XML with PHP 5
                              Chapter 9:           Mainstream Extensions
                              Chapter 10:          Using PEAR
                              Chapter 11:          Important PEAR Packages
                              Chapter 12:          Building PEAR Components
                              Chapter 13:          Making the Move
                              Chapter 14:          Performance
                              Chapter 15:          An Introduction to Writing PHP Extensions
                              Chapter 16:          PHP Shell Scripting
                                       A.          PEAR and PECL Package Index
                                       B.          phpDocumentor Format Reference
                                       C.          Zend Studio Quick Start
                                  Index
Gutmans_Frontmatter Page viii Thursday, September 23, 2004 9:05 AM
Gutmans_TOC Page ix Thursday, September 23, 2004 9:06 AM




          Contents

                  Foreword............................................................................................................. xxi

                  Preface ................................................................................................................xxii

              1 What Is New in PHP 5? ........................................................................................1
                1.1 Introduction ........................................................................................................ 1
                1.2 Language Features ............................................................................................. 1
                   1.2.1 New Object-Oriented Model........................................................................ 1
                   1.2.2 New Object-Oriented Features................................................................... 3
                   1.2.3 Other New Language Features .................................................................. 7
                1.3 General PHP Changes........................................................................................ 8
                   1.3.1 XML and Web Services ............................................................................... 8
                1.4 Other New Features in PHP 5 ......................................................................... 11
                   1.4.1 New Memory Manager.............................................................................. 11
                   1.4.2 Dropped Support for Windows 95............................................................. 11
                1.5 Summary........................................................................................................... 11

              2 PHP 5 Basic Language .......................................................................................13
                2.1 Introduction ...................................................................................................... 13
                2.2 HTML Embedding ............................................................................................ 14
                2.3 Comments ......................................................................................................... 14
                2.4 Variables............................................................................................................ 15
                   2.4.1 Indirect References to Variables .............................................................. 16
                   2.4.2 Managing Variables .................................................................................. 16
                   2.4.3 Superglobals .............................................................................................. 18
                2.5 Basic Data Types .............................................................................................. 18
                   2.5.1 Integers ...................................................................................................... 19
                   2.5.2 Floating-Point Numbers ........................................................................... 19
                   2.5.3 Strings........................................................................................................ 19
                   2.5.4 Booleans ..................................................................................................... 22
                   2.5.5 Null ............................................................................................................ 23

                                                                                                                                           ix
Gutmans_TOC Page x Thursday, September 23, 2004 9:06 AM




       x                                                                                                                       Contents


                 2.5.6 Resources ...................................................................................................23
                 2.5.7 Arrays.........................................................................................................23
                 2.5.8 Constants ...................................................................................................30
              2.6 Operators...........................................................................................................31
                 2.6.1 Binary Operators .......................................................................................32
                 2.6.2 Assignment Operators...............................................................................32
                 2.6.3 Comparison Operators ..............................................................................33
                 2.6.4 Logical Operators ......................................................................................34
                 2.6.5 Bitwise Operators ......................................................................................35
                 2.6.6 Unary Operators........................................................................................36
                 2.6.7 Negation Operators ...................................................................................36
                 2.6.8 Increment/Decrement Operators ..............................................................37
                 2.6.9 The Cast Operators ...................................................................................38
                 2.6.10 The Silence Operator...............................................................................39
                 2.6.11 The One and Only Ternary Operator .....................................................39
              2.7 Control Structures ............................................................................................39
                 2.7.1 Conditional Control Structures.................................................................39
                 2.7.2 Loop Control Structures ............................................................................42
                 2.7.3 Code Inclusion Control Structures ...........................................................45
              2.8 Functions ...........................................................................................................48
                 2.8.1 User-Defined Functions ............................................................................49
                 2.8.2 Function Scope...........................................................................................49
                 2.8.3 Returning Values By Value ......................................................................50
                 2.8.4 Returning Values By Reference................................................................51
                 2.8.5 Declaring Function Parameters................................................................52
                 2.8.6 Static Variables .........................................................................................53
              2.9 Summary ...........................................................................................................54

           3 PHP 5 OO Language .......................................................................................... 55
             3.1 Introduction.......................................................................................................55
             3.2 Objects ...............................................................................................................55
             3.3 Declaring a Class ..............................................................................................57
             3.4 The new Keyword and Constructors ................................................................57
             3.5 Destructors ........................................................................................................58
             3.6 Accessing Methods and Properties Using the $this Variable.......................59
                3.6.1 public, protected, and private Properties .......................................60
                3.6.2 public, protected, and private Methods ..........................................61
                3.6.3 Static Properties ........................................................................................62
                3.6.4 Static Methods ...........................................................................................64
             3.7 Class Constants.................................................................................................65
             3.8 Cloning Objects .................................................................................................66
             3.9 Polymorphism....................................................................................................67
             3.10 parent:: and self::........................................................................................70
             3.11 instanceof Operator....................................................................................71
Gutmans_TOC Page xi Thursday, September 23, 2004 9:06 AM




          Contents                                                                                                                        xi


                  3.12 Abstract Methods and Classes ....................................................................... 72
                  3.13 Interfaces ........................................................................................................ 73
                  3.14 Inheritance of Interfaces ................................................................................ 75
                  3.15 final Methods ............................................................................................... 75
                  3.16 final Classes ................................................................................................. 76
                  3.17 __toString() Method.................................................................................. 76
                  3.18 Exception Handling ........................................................................................ 77
                  3.19 __autoload() ............................................................................................... 80
                  3.20 Class Type Hints in Function Parameters .................................................... 82
                  3.21 Summary......................................................................................................... 83

              4 PHP 5 Advanced OOP and Design Patterns .................................................85
                4.1 Introduction ...................................................................................................... 85
                4.2 Overloading Capabilities.................................................................................. 85
                   4.2.1 Property and Method Overloading ........................................................... 85
                   4.2.2 Overloading the Array Access Syntax...................................................... 88
                4.3 Iterators ............................................................................................................ 89
                4.4 Design Patterns ................................................................................................ 94
                   4.4.1 Strategy Pattern........................................................................................ 95
                   4.4.2 Singleton Pattern ...................................................................................... 97
                   4.4.3 Factory Pattern ......................................................................................... 98
                   4.4.4 Observer Pattern ..................................................................................... 101
                4.5 Reflection......................................................................................................... 103
                   4.5.1 Introduction ............................................................................................. 103
                   4.5.2 Reflection API.......................................................................................... 103
                   4.5.3 Reflection Examples................................................................................ 106
                   4.5.4 Implementing the Delegation Pattern Using Reflection....................... 107
                4.6 Summary......................................................................................................... 109

              5 How to Write a Web Application with PHP.................................................111
                5.1 Introduction .................................................................................................... 111
                5.2 Embedding into HTML .................................................................................. 112
                5.3 User Input ....................................................................................................... 114
                5.4 Safe-Handling User Input.............................................................................. 117
                   5.4.1 Common Mistakes ................................................................................... 117
                5.5 Techniques to Make Scripts “Safe” ................................................................ 120
                   5.5.1 Input Validation ...................................................................................... 120
                   5.5.2 HMAC Verification.................................................................................. 122
                   5.5.3 PEAR::Crypt_HMAC............................................................................... 124
                   5.5.4 Input Filter .............................................................................................. 127
                   5.5.5 Working with Passwords ........................................................................ 127
                   5.5.6 Error Handling ........................................................................................ 129
                5.6 Cookies ............................................................................................................ 131
                5.7 Sessions ........................................................................................................... 134
Gutmans_TOC Page xii Thursday, September 23, 2004 9:06 AM




       xii                                                                                                                     Contents


                5.8 File Uploads ....................................................................................................137
                   5.8.1 Handling the Incoming Uploaded File ...................................................138
                5.9 Architecture.....................................................................................................143
                   5.9.1 One Script Serves All ..............................................................................143
                   5.9.2 One Script per Function ..........................................................................144
                   5.9.3 Separating Logic from Layout ................................................................144
                5.10 Summary .......................................................................................................146

             6 Databases with PHP 5 ..................................................................................... 149
               6.1 Introduction.....................................................................................................149
               6.2 MySQL.............................................................................................................149
                  6.2.1 MySQL Strengths and Weaknesses .......................................................150
                  6.2.2 PHP Interface ..........................................................................................150
                  6.2.3 Example Data ..........................................................................................151
                  6.2.4 Connections..............................................................................................151
                  6.2.5 Buffered Versus Unbuffered Queries .....................................................153
                  6.2.6 Queries .....................................................................................................154
                  6.2.7 Multi Statements.....................................................................................155
                  6.2.8 Fetching Modes........................................................................................156
                  6.2.9 Prepared Statements...............................................................................156
                  6.2.10 BLOB Handling .....................................................................................158
               6.3 SQLite..............................................................................................................160
                  6.3.1 SQLite Strengths and Weaknesses ........................................................160
                  6.3.2 Best Areas of Use.....................................................................................161
                  6.3.3 PHP Interface ..........................................................................................162
               6.4 PEAR DB .........................................................................................................176
                  6.4.1 Obtaining PEAR DB................................................................................176
                  6.4.2 Pros and Cons of Database Abstraction .................................................177
                  6.4.3 Which Features Are Abstracted? ............................................................177
                  6.4.4 Database Connections .............................................................................178
                  6.4.5 Executing Queries ...................................................................................180
                  6.4.6 Fetching Results ......................................................................................182
                  6.4.7 Sequences .................................................................................................184
                  6.4.8 Portability Features ................................................................................185
                  6.4.9 Abstracted Errors ....................................................................................186
                  6.4.10 Convenience Methods............................................................................188
               6.5 Summary .........................................................................................................190

             7 Error Handling.................................................................................................. 191
               7.1 Introduction.....................................................................................................191
               7.2 Types of Errors ................................................................................................192
                  7.2.1 Programming Errors ...............................................................................192
                  7.2.2 Undefined Symbols..................................................................................194
                  7.2.3 Portability Errors ....................................................................................197
Gutmans_TOC Page xiii Thursday, September 23, 2004 9:06 AM




           Contents                                                                                                                     xiii


                     7.2.4 Runtime Errors........................................................................................ 201
                     7.2.5 PHP Errors .............................................................................................. 201
                  7.3 PEAR Errors ................................................................................................... 206
                     7.3.1 The PEAR_Error Class ........................................................................... 209
                     7.3.2 Handling PEAR Errors ........................................................................... 212
                     7.3.3 PEAR Error Modes.................................................................................. 213
                     7.3.4 Graceful Handling ................................................................................... 213
                  7.4 Exceptions ....................................................................................................... 216
                     7.4.1 What Are Exceptions? ............................................................................. 216
                     7.4.2 try, catch, and throw ............................................................................... 216
                  7.5 Summary......................................................................................................... 218

              8 XML with PHP 5 ................................................................................................219
                8.1 Introduction .................................................................................................... 219
                8.2 Vocabulary....................................................................................................... 220
                8.3 Parsing XML ................................................................................................... 222
                   8.3.1 SAX .......................................................................................................... 222
                   8.3.2 DOM ......................................................................................................... 226
                8.4 SimpleXML ..................................................................................................... 231
                   8.4.1 Creating a SimpleXML Object................................................................ 232
                   8.4.2 Browsing SimpleXML Objects ................................................................ 233
                   8.4.3 Storing SimpleXML Objects ................................................................... 234
                8.5 PEAR ............................................................................................................... 234
                   8.5.1 XML_Tree ................................................................................................ 235
                   8.5.2 XML_RSS................................................................................................. 236
                8.6 Converting XML ............................................................................................. 239
                   8.6.1 XSLT ........................................................................................................ 239
                8.7 Communicating with XML............................................................................. 244
                   8.7.1 XML-RPC................................................................................................. 244
                   8.7.2 SOAP........................................................................................................ 252
                8.8 Summary......................................................................................................... 259

              9 Mainstream Extensions ...................................................................................261
                9.1 Introduction .................................................................................................... 261
                9.2 Files and Streams ........................................................................................... 261
                   9.2.1 File Access ............................................................................................... 262
                   9.2.2 Program Input/Output ............................................................................ 264
                   9.2.3 Input/Output Streams............................................................................. 267
                   9.2.4 Compression Streams ............................................................................. 268
                   9.2.5 User Streams ........................................................................................... 270
                   9.2.6 URL Streams ........................................................................................... 271
                   9.2.7 Locking .................................................................................................... 276
                   9.2.8 Renaming and Removing Files............................................................... 277
                   9.2.9 Temporary Files ...................................................................................... 278
Gutmans_TOC Page xiv Thursday, September 23, 2004 9:06 AM




       xiv                                                                                                                   Contents


              9.3 Regular Expressions .......................................................................................279
                 9.3.1 Syntax ......................................................................................................279
                 9.3.2 Functions..................................................................................................293
              9.4 Date Handling .................................................................................................301
                 9.4.1 Retrieving Date and Time Information ..................................................301
                 9.4.2 Formatting Date and Time .....................................................................305
                 9.4.3 Parsing Date Formats .............................................................................313
              9.5 Graphics Manipulation with GD....................................................................314
                 9.5.1 Case 1: Bot-Proof Submission Forms .....................................................315
                 9.5.2 Case 2: Bar Chart ....................................................................................320
                 9.5.3 Exif..........................................................................................................326
              9.6 Multi-Byte Strings and Character Sets .........................................................329
                 9.6.1 Character Set Conversions......................................................................330
                 9.6.2 Extra Functions Dealing with Multi-Byte Character Sets ...................335
                 9.6.3 Locales......................................................................................................340
              9.7 Summary .........................................................................................................343

         10 Using PEAR........................................................................................................ 345
            10.1 Introduction...................................................................................................345
            10.2 PEAR Concepts .............................................................................................346
              10.2.1 Packages.................................................................................................346
              10.2.2 Releases..................................................................................................346
              10.2.3 Version Numbers ...................................................................................347
            10.3 Obtaining PEAR............................................................................................349
              10.3.1 Installing with UNIX / Linux PHP Distribution .................................350
              10.3.2 Installing with PHP Windows Installer ...............................................351
              10.3.3 go-pear.org .............................................................................................351
            10.4 Installing Packages .......................................................................................354
              10.4.1 Using the pear Command ...................................................................354
            10.5 Configuration Parameters ............................................................................358
            10.6 PEAR Commands..........................................................................................364
              10.6.1 pear install ......................................................................................364
              10.6.2 pear list .............................................................................................368
              10.6.3 pear info .............................................................................................369
              10.6.4 pear list-all ....................................................................................370
              10.6.5 pear list-upgrades .........................................................................370
              10.6.6 pear upgrade ......................................................................................371
              10.6.7 pear upgrade-all..............................................................................372
              10.6.8 pear uninstall ..................................................................................373
              10.6.9 pear search ........................................................................................373
              10.6.10 pear remote-list............................................................................374
              10.6.11 pear remote-info............................................................................375
              10.6.12 pear download ..................................................................................375
              10.6.13 pear config-get ..............................................................................376
Gutmans_TOC Page xv Thursday, September 23, 2004 9:06 AM




          Contents                                                                                                                    xv


                   10.6.14 pear config-set ............................................................................. 376
                   10.6.15 pear config-show ........................................................................... 376
                   10.6.16 Shortcuts.............................................................................................. 377
                 10.7 Installer Front-Ends..................................................................................... 378
                   10.7.1 CLI (Command Line Interface) Installer ............................................. 378
                   10.7.2 Gtk Installer .......................................................................................... 378
                 10.8 Summary....................................................................................................... 381

            11 Important PEAR Packages .............................................................................383
               11.1 Introduction .................................................................................................. 383
               11.2 Database Queries.......................................................................................... 383
               11.3 Template Systems......................................................................................... 383
                 11.3.1 Template Terminology .......................................................................... 384
                 11.3.2 HTML_Template_IT ............................................................................. 384
                 11.3.3 HTML_Template_Flexy ....................................................................... 387
               11.4 Authentication .............................................................................................. 392
                 11.4.1 Overview ................................................................................................ 392
                 11.4.2 Example: Auth with Password File...................................................... 393
                 11.4.3 Example: Auth with DB and User Data .............................................. 394
                 11.4.4 Auth Security Considerations............................................................... 396
                 11.4.5 Auth Scalability Considerations........................................................... 397
                 11.4.6 Auth Summary ...................................................................................... 398
               11.5 Form Handling.............................................................................................. 398
                 11.5.1 HTML_QuickForm.................................................................................. 398
                 11.5.2 Example: Login Form............................................................................ 399
                 11.5.3 Receiving Data....................................................................................... 399
               11.6 Caching.......................................................................................................... 399
                 11.6.1 Cache_Lite .......................................................................................... 399
               11.7 Summary....................................................................................................... 401

            12 Building PEAR Components ..........................................................................403
               12.1 Introduction .................................................................................................. 403
               12.2 PEAR Standards........................................................................................... 403
                 12.2.1 Symbol Naming ..................................................................................... 403
                 12.2.2 Indentation ............................................................................................ 406
               12.3 Release Versioning........................................................................................ 408
               12.4 CLI Environment.......................................................................................... 408
               12.5 Fundamentals ............................................................................................... 410
                 12.5.1 When and How to Include Files............................................................ 410
                 12.5.2 Error Handling ...................................................................................... 411
               12.6 Building Packages ........................................................................................ 411
                 12.6.1 PEAR Example: HelloWorld ................................................................. 411
                 12.6.2 Building the Tarball.............................................................................. 414
                 12.6.3 Verification ............................................................................................ 414
                 12.6.4 Regression Tests.................................................................................... 416
Gutmans_TOC Page xvi Thursday, September 23, 2004 9:06 AM




       xvi                                                                                                                Contents


              12.7 The package.xml Format ..............................................................................416
                12.7.1 Package Information .............................................................................417
                12.7.2 Release Information ..............................................................................419
              12.8 Dependencies.................................................................................................423
                12.8.1 Element: <deps> ...................................................................................423
                12.8.2 Element: <dep> .....................................................................................423
                12.8.3 Dependency Types .................................................................................424
                12.8.4 Reasons to Avoid Dependencies............................................................425
                12.8.5 Optional Dependencies..........................................................................426
                12.8.6 Some Examples......................................................................................426
              12.9 String Substitutions......................................................................................427
                12.9.1 Element: <replace> .............................................................................427
                12.9.2 Examples................................................................................................427
              12.10 Including C Code.........................................................................................428
                12.10.1 Element: <configureoptions> .......................................................428
                12.10.2 Element: <configureoption> .........................................................428
              12.11 Releasing Packages .....................................................................................428
              12.12 The PEAR Release Process.........................................................................429
              12.13 Packaging ....................................................................................................430
                12.13.1 Source Analysis....................................................................................430
                12.13.2 MD5 Checksum Generation ................................................................430
                12.13.3 Package.xml Update............................................................................431
                12.13.4 Tarball Creation ..................................................................................431
              12.14 Uploading ....................................................................................................432
                12.14.1 Upload Release ....................................................................................432
                12.14.2 Finished!...............................................................................................432
              12.15 Summary .....................................................................................................432

         13 Making the Move .............................................................................................. 433
            13.1 Introduction...................................................................................................433
            13.2 The Object Model ..........................................................................................433
            13.3 Passing Objects to Functions........................................................................433
            13.4 Compatibility Mode.......................................................................................435
              13.4.1 Casting Objects ......................................................................................435
              13.4.2 Comparing Objects ................................................................................436
            13.5 Other Changes ..............................................................................................437
              13.5.1 Assigning to $this ................................................................................437
              13.5.2 get_class .............................................................................................440
            13.6 E_STRICT ......................................................................................................441
              13.6.1 Automagically Creating Objects ...........................................................441
              13.6.2 var and public ....................................................................................441
              13.6.3 Constructors...........................................................................................442
              13.6.4 Inherited Methods .................................................................................442
              13.6.5 Define Classes Before Usage.................................................................443
Gutmans_TOC Page xvii Thursday, September 23, 2004 9:06 AM




          Contents                                                                                                                   xvii


                  13.7 Other Compatibility Problems ..................................................................... 443
                    13.7.1 Command-Line Interface ...................................................................... 443
                    13.7.2 Comment Tokens................................................................................... 443
                    13.7.3 MySQL ................................................................................................... 445
                  13.8 Changes in Functions ................................................................................... 445
                    13.8.1 array_merge() .................................................................................... 445
                    13.8.2 strrpos() and strripos()............................................................... 446
                  13.9 Summary....................................................................................................... 447

            14 Performance .......................................................................................................449
               14.1 Introduction .................................................................................................. 449
               14.2 Design for Performance ................................................................................ 449
                 14.2.1 PHP Design Tip #1: Beware of State ................................................... 450
                 14.2.2 PHP Design Tip #2: Cache!................................................................... 451
                 14.2.3 PHP Design Tip #3: Do Not Over Design!............................................ 456
               14.3 Benchmarking............................................................................................... 457
                 14.3.1 Using ApacheBench .............................................................................. 457
                 14.3.2 Using Siege ............................................................................................ 458
                 14.3.3 Testing Versus Real Traffic .................................................................. 459
               14.4 Profiling with Zend Studio's Profiler ........................................................... 459
               14.5 Profiling with APD........................................................................................ 461
                 14.5.1 Installing APD....................................................................................... 461
                 14.5.2 Analyzing Trace Data ........................................................................... 462
               14.6 Profiling with Xdebug................................................................................... 465
                 14.6.1 Installing Xdebug .................................................................................. 466
                 14.6.2 Tracing Script Execution ...................................................................... 466
                 14.6.3 Using KCachegrind ............................................................................... 468
               14.7 Using APC (Advanced PHP Cache) ............................................................. 470
               14.8 Using ZPS (Zend Performance Suite) .......................................................... 470
                 14.8.1 Automatic Optimization........................................................................ 471
                 14.8.2 Compiled Code Caching ........................................................................ 472
                 14.8.3 Dynamic Content Caching .................................................................... 473
                 14.8.4 Content Compression ............................................................................ 476
               14.9 Optimizing Code ........................................................................................... 477
                 14.9.1 Micro-Benchmarks ................................................................................ 477
                 14.9.2 Rewrite in C........................................................................................... 479
                 14.9.3 OO Versus Procedural Code ................................................................. 480
               14.10 Summary..................................................................................................... 481

            15 An Introduction to Writing PHP Extensions..............................................483
               15.1 Introduction .................................................................................................. 483
               15.2 Quickstart ..................................................................................................... 484
                 15.2.1 Memory Management ........................................................................... 489
                 15.2.2 Returning Values from PHP Functions ............................................... 490
                 15.2.3 Completing self-concat()................................................................ 490
                 15.2.4 Summary of Example............................................................................ 492
                 15.2.5 Wrapping Third-Party Extensions ....................................................... 492
Gutmans_TOC Page xviii Thursday, September 23, 2004 9:06 AM




       xviii                                                                                                                 Contents


                 15.2.6 Global Variables ....................................................................................501
                 15.2.7 Adding Custom INI Directives..............................................................503
                 15.2.8 Thread-Safe Resource Manager Macros...............................................504
               15.3 Summary .......................................................................................................505

         16 PHP Shell Scripting ......................................................................................... 507
            16.1 Introduction...................................................................................................507
            16.2 PHP CLI Shell Scripts ..................................................................................508
              16.2.1 How CLI Differs From CGI ...................................................................508
              16.2.2 The Shell-Scripting Environment.........................................................510
              16.2.3 Parsing Command-Line Options ..........................................................512
              16.2.4 Good Practices........................................................................................515
              16.2.5 Process Control ......................................................................................516
              16.2.6 Examples................................................................................................520
            16.3 Summary .......................................................................................................526

          A PEAR and PECL Package Index ................................................................... 527
            A.1 Authentication ................................................................................................527
            A.2 Benchmarking ................................................................................................530
            A.3 Caching ...........................................................................................................530
            A.4 Configuration ..................................................................................................531
            A.5 Console ............................................................................................................531
            A.6 Database .........................................................................................................533
            A.7 Date and Time ................................................................................................542
            A.8 Encryption ......................................................................................................543
            A.9 File Formats....................................................................................................545
            A.10 File System ...................................................................................................548
            A.11 Gtk Components ...........................................................................................550
            A.12 HTML............................................................................................................550
            A.13 HTTP.............................................................................................................561
            A.14 Images ...........................................................................................................563
            A.15 Internationalization .....................................................................................566
            A.16 Logging..........................................................................................................568
            A.17 Mail ...............................................................................................................569
            A.18 Math ..............................................................................................................571
            A.19 Networking ...................................................................................................574
            A.20 Numbers........................................................................................................584
            A.21 Payment ........................................................................................................585
            A.22 PEAR............................................................................................................587
            A.23 PHP ...............................................................................................................588
            A.24 Processing .....................................................................................................594
            A.25 Science...........................................................................................................594
            A.26 Streams .........................................................................................................595
            A.27 Structures .....................................................................................................596
            A.28 System...........................................................................................................598
            A.29 Text................................................................................................................599
Gutmans_TOC Page xix Thursday, September 23, 2004 9:06 AM




          Contents                                                                                                                       xix


                  A.30 Tools and Utilities ........................................................................................ 600
                  A.31 Web Services................................................................................................. 603
                  A.32 XML .............................................................................................................. 604

             B phpDocumentor Format Reference ..............................................................613
               B.1 Introduction .................................................................................................... 613
               B.2 Documentation Comments ............................................................................ 613
               B.3 Tag Reference ................................................................................................. 615
                 B.3.1 abstract ................................................................................................ 615
                 B.3.2 access .................................................................................................... 616
                 B.3.3 author .................................................................................................... 617
                 B.3.4 category ................................................................................................ 618
                 B.3.5 copyright.............................................................................................. 618
                 B.3.6 deprecated............................................................................................ 618
                 B.3.7 example .................................................................................................. 619
                 B.3.8 filesource............................................................................................ 620
                 B.3.9 final ...................................................................................................... 620
                 B.3.10 global ................................................................................................ 621
                 B.3.11 ignore ................................................................................................ 622
                 B.3.12 inheritdoc (inline) .......................................................................... 622
                 B.3.13 internal, internal (inline) ........................................................ 622
                 B.3.14 licence .............................................................................................. 623
                 B.3.15 link .................................................................................................... 623
                 B.3.16 link (inline) ...................................................................................... 623
                 B.3.17 name .................................................................................................... 624
                 B.3.18 package .............................................................................................. 624
                 B.3.19 param .................................................................................................. 626
                 B.3.20 return ................................................................................................ 627
                 B.3.21 see........................................................................................................ 627
                 B.3.22 since .................................................................................................. 628
                 B.3.23 static ................................................................................................. 628
                 B.3.24 staticvar........................................................................................... 629
                 B.3.25 subpackage......................................................................................... 629
                 B.3.26 todo...................................................................................................... 630
                 B.3.27 uses .................................................................................................... 630
                 B.3.28 var........................................................................................................ 631
                 B.3.29 version ............................................................................................... 631
               B.4 Tag Table......................................................................................................... 632
               B.5 Using the phpDocumentor Tool ..................................................................... 633

             C Zend Studio Quick Start Guide ....................................................................643
               C.1 Version 3.5.x ................................................................................................... 643
               C.2 About the Zend Studio Client Quick Start Guide......................................... 643
               C.3 About Zend ..................................................................................................... 643
               C.4 Zend Studio Client: Overview........................................................................ 644
Gutmans_TOC Page xx Thursday, September 23, 2004 9:06 AM




       xx                                                                                                                      Contents


                C.4.1 Studio Components .................................................................................644
                C.4.2 Client Server Configuration ...................................................................645
                C.4.3 Installation and Registration .................................................................645
              C.5 Editing a File ..................................................................................................647
                C.5.1 Editing a File...........................................................................................647
              C.6 Working with Projects ....................................................................................648
                C.6.1 Advantages of Working with Projects....................................................648
                C.6.2 How to Create a Project ..........................................................................648
              C.7 Running the Debugger ..................................................................................648
                C.7.1 Internal Debugger...................................................................................649
                C.7.2 Remote Debugger ....................................................................................649
                C.7.3 Debug URL ..............................................................................................650
              C.8 Configure Studio Server for Remote Debugger and Profiling ......................650
              C.9 Running the Profiler.......................................................................................651
              C.10 Product Support............................................................................................652
                C.10.1 Getting Support.....................................................................................653
              C.11 Main Features...............................................................................................653

              Index.................................................................................................................... 655
Gutmans_PrefaceFore Page xxi Thursday, September 23, 2004 9:06 AM




           Foreword




                      Within the last few years, PHP has grown to be the most widespread web plat-
                      form in the world, operational in more than a third of the web servers across
                      the globe. PHP's growth is not only quantitative but also qualitative. More and
                      more companies, including Fortune companies, rely on PHP to run their busi-
                      ness-critical applications, which creates new jobs and increases the demand
                      for PHP developers. Version 5, due to be released in the very near future, holds
                      an even greater promise.
                           While the complexity of starting off with PHP remains unchanged and
                      very low, the features offered by PHP today enable developers to reach far
                      beyond simple HTML applications. The revised object model allows for large-
                      scale projects to be written efficiently, using standard object-oriented method-
                      ologies. New XML support makes PHP the best language available for pro-
                      cessing XML and, coupled with new SOAP support, an ideal platform for
                      creating and using Web Services.
                           This book, written by my colleague, Andi Gutmans, and two very promi-
                      nent PHP developers, Stig Bakken and Derick Rethans, holds the key to
                      unlocking the riches of PHP 5. It thoroughly covers all of the features of the
                      new version, and is a must-have for all PHP developers who are interested in
                      exploring PHP 5's advanced features.

                      Zeev Suraski
                                                                                                   xxi
Gutmans_PrefaceFore Page xxii Thursday, September 23, 2004 9:06 AM




       xxii                                                                              Preface




       Preface




                  “The best security against revolution is in constant correction of abuses and
                  the introduction of needed improvements. It is the neglect of timely repair
                  that makes rebuilding necessary.”—Richard Whately


                  IN THE BEGINNING
                  It was eight years ago, when Rasmus Lerdorf first started developing PHP/FI.
                  He could not have imagined that his creation would eventually lead to the
                  development of PHP as we know it today, which is being used by millions of
                  people. The first version of “PHP/FI,” called Personal Homepage Tools/
                  Form Interpreter, was a collection of Perl scripts in 1995.1 One of the basic
                  features was a Perl-like language for handling form submissions, but it lacked
                  many common useful language features, such as for loops.




                  1
                      http://groups.google.com/groups?selm=3r7pgp$aa1@ionews.io.org.
Gutmans_PrefaceFore Page xxiii Thursday, September 23, 2004 9:06 AM




            In the Beginning                                                                        xxiii


                      PHP/FI 2
                      A rewrite came with PHP/FI 22 in 1997, but at that time the development was
                      almost solely handled by Rasmus. After its release in November of that year,
                      Andi Gutmans and Zeev Suraski bumped into PHP/FI while looking for a lan-
                      guage to develop an e-commerce solution as a university project. They discov-
                      ered that PHP/FI was not quite as powerful as it seemed, and its language was
                      lacking many common features. One of the most interesting aspects included
                      the way while loops were implemented. The hand-crafted lexical scanner would
                      go through the script and when it hit the while keyword it would remember its
                      position in the file. At the end of the loop, the file pointer sought back to the
                      saved position, and the whole loop was reread and re-executed.


                      PHP 3
                      Zeev and Andi decided to completely rewrite the scripting language. They then
                      teamed up with Rasmus to release PHP 3, and along also came a new name: PHP:
                      Hypertext Preprocessor, to emphasize that PHP was a different product and not
                      only suitable for personal use. Zeev and Andi had also designed and implemented
                      a new extension API. This new API made it possible to easily support additional
                      extensions for performing tasks such as accessing databases, spell checkers and
                      other technologies, which attracted many developers who were not part of the
                      “core” group to join and contribute to the PHP project. At the time of PHP 3’s
                      release3 in June 1998, the estimated PHP installed base consisted of about 50,000
                      domains. PHP 3 sparked the beginning of PHP’s real breakthrough, and was the
                      first version to have an installed base of more than one million domains.


                      PHP 4
                      In late 1998, Zeev and Andi looked back at their work in PHP 3 and felt they
                      could have written the scripting language even better, so they started yet
                      another rewrite. While PHP 3 still continuously parsed the scripts while execut-
                      ing them, PHP 4 came with a new paradigm of “compile first, execute later.” The
                      compilation step does not compile PHP scripts into machine code; it instead
                      compiles them into byte code, which is then executed by the Zend Engine
                      (Zend stands for Zeev & Andi), the new heart of PHP 4. Because of this new
                      way of executing scripts, the performance of PHP 4 was much better than that
                      of PHP 3, with only a small amount of backward compatibility breakage4.
                      Among other improvements was an improved extension API for better run-time
                      performance, a web server abstraction layer allowing PHP 4 to run on most pop-
                      ular web servers, and lots more. PHP 4 was officially released on May 22, 2002,
                      and today its installed base has surpassed 15 million domains.

                      2
                          http://groups.google.com/groups?selm=Dn1JM9.61t%40gpu.utcc.utoronto.ca.
                      3
                        http://groups.google.com/groups?selm=Pine.WNT.3.96.980606130654.-317675I-
                        100000%40shell.lerdorf.on.ca.
                      4
                        http://www.php.net/manual/en/migration4.php.
Gutmans_PrefaceFore Page xxiv Thursday, September 23, 2004 9:06 AM




       xxiv                                                                              Preface


                       In PHP 3, the minor version number (the middle digit) was never used,
                  and all versions were numbered as 3.0.x. This changed in PHP 4, and the minor
                  version number was used to denote important changes in the language. The first
                  important change came in PHP 4.1.0,5 which introduced superglobals such as
                  $_GET and $_POST. Superglobals can be accessed from within functions without
                  having to use the global keyword. This feature was added in order to allow the
                  register_globals INI option to be turned off. register_globals is a feature in
                  PHP which automatically converts input variables like "?foo=bar" in http://
                  php.net/?foo=bar to a PHP variable called $foo. Because many people do not
                  check input variables properly, many applications had security holes, which
                  made it quite easy to circumvent security and authentication code.
                       With the new superglobals in place, on April 22, 2002, PHP 4.2.0 was
                  released with the register_globals turned off by default. PHP 4.3.0, the last
                  significant PHP 4 version, was released on December 27, 2002. This version
                  introduced the Command Line Interface (CLI), a revamped file and net-
                  work I/O layer (called streams), and a bundled GD library. Although most of
                  those additions have no real effect on end users, the major version was
                  bumped due to the major changes in PHP’s core.


                  PHP 5
                  Soon after, the demand for more common object-oriented features increased
                  immensely, and Andi came up with the idea of rewriting the objected-oriented
                  part of the Zend Engine. Zeev and Andi wrote the “Zend Engine II: Feature
                  Overview and Design” document6 and jumpstarted heated discussions about
                  PHP’s future. Although the basic language has stayed the same, many fea-
                  tures were added, dropped, and changed by the time PHP 5 matured. For
                  example, namespaces and multiple inheritance, which were mentioned in the
                  original document, never made it into PHP 5. Multiple inheritance was
                  dropped in favor of interfaces, and namespaces were dropped completely. You
                  can find a full list of new features in Chapter, “What Is New in PHP 5?”
                       PHP 5 is expected to maintain and even increase PHP’s leadership in
                  the web development market. Not only does it revolutionizes PHP’s object-
                  oriented support but it also contains many new features which make it the
                  ultimate web development platform. The rewritten XML functionality in
                  PHP 5 puts it on par with other web technologies in some areas and over-
                  takes them in others, especially due to the new SimpleXML extension which
                  makes it ridiculously easy to manipulate XML documents. In addition, the
                  new SOAP, MySQLi, and variety of other extensions are significant mile-
                  stones in PHP’s support for additional technologies.



                  5
                      http://www.php.net/release_4_1_0.php.
                  6
                      http://zend.com/engine2/ZendEngine-2.0.pdf.
Gutmans_PrefaceFore Page xxv Thursday, September 23, 2004 9:06 AM




            Audience                                                                              xxv



                      AUDIENCE
                      This book is an introduction to the advanced features new to PHP 5. It is writ-
                      ten for PHP programmers who are making the move to PHP 5. Although
                      Chapter 2, “PHP 5 Basic Language,” contains an introduction to PHP 5 syn-
                      tax, it is meant as a refresher for PHP programmers and not as a tutorial for
                      new programmers. However, web developers with experience programming
                      other high-level languages may indeed find that this tutorial is all they need
                      in order to begin working effectively with PHP 5.


                      CHAPTER OVERVIEW
                      Chapter 1, “What Is New in PHP 5?” discusses the new features in PHP 5.
                      Most of these new features deal with new object-oriented features, including
                      small examples for each feature. It also gives an overview of the new exten-
                      sions in PHP 5. Most of the topics mentioned in this chapter are explained in
                      more detail in later chapters.
                            Chapter 2, “PHP 5 Basic Language,” introduces the PHP syntax to those
                      readers not familiar with PHP. All basic language constructs and variable
                      types are explained along with simple examples to give the reader the neces-
                      sary building blocks to build real scripts.
                            Chapter 3, “PHP 5 OO Language,” continues exploring PHP 5's syntax,
                      focusing on its object-oriented functionality. This chapter covers basics, such
                      as properties and methods, and progresses to more complicated subjects, such
                      as polymorphism, interfaces, exceptions, and lots more.
                            Using the previous chapter as a foundation, Chapter 4, “PHP 5 Advanced
                      OOP and Design Patterns,” covers some of the most advanced features of PHP
                      5’s object model. After learning these features, including four commonly used
                      design patterns and PHP’s reflection capabilities, you will soon become an OO
                      wizard.
                            Now that you are familiar with the syntax and language features of PHP,
                      Chapter 5, “How to Write a Web Application with PHP,” introduces you to the
                      world of writing web applications. The authors show you basics, such as han-
                      dling input through form variables and safety techniques, but this chapter
                      also includes more advanced topics, such as handling sessions with cookies
                      and PHP's session extension. You also find a few tips on laying out your source
                      code for your web applications.
                            Chapter 6, “Databases with PHP 5,” introduces using MySQL, SQLite,
                      and Oracle from PHP, but focuses primarily on the PHP 5-specific details of
                      database access. For each database, you learn about some of its strong and
                      weak points, as well as the types of applications at which each excels. And of
                      course, you learn how to interface with them using PHP's native functions or
                      using PEAR DB.
Gutmans_PrefaceFore Page xxvi Thursday, September 23, 2004 9:06 AM




       xxvi                                                                                Preface


                        All scripts can throw errors, but of course you do not want them to show
                  up on your web site once your application has passed its development state.
                  Chapter 7, “Error Handling,” deals with different types of errors that exist,
                  how to handle those errors with PHP, and how to handle errors with PEAR.
                        As one of the important new features in PHP 5 is its renewed XML sup-
                  port, a chapter on XML features in PHP 5 could not be missed. Chapter 8,
                  “XML with PHP 5,” talks about the different strategies of parsing XML and
                  converting XML to other formats with XSLT. XML-RPC and SOAP are intro-
                  duced to show you how to implement web services with both techniques.
                        Although not specifically for PHP 5, the five mainstream extensions that
                  Chapter 9,“Mainstream Extensions,” covers are important enough to deserve a
                  place in this book. The first section, “Files and Streams,” explains about han-
                  dling files and network streams. A stream is nothing more than a way to
                  access external data, such as a file, remote URL, or compressed file. The sec-
                  ond section, “Regular Expressions,” explains the syntax of a regular expres-
                  sion engine (PCRE) that PHP uses with numerous examples to show you how
                  these expressions can make your life easier. In “Date Handling,” we explain
                  the different functions used to parse and format date and time strings. In
                  “Graphics Manipulation with GD,” we show you through two real-life scenar-
                  ios the basic functions of creating and manipulating graphics with PHP. The
                  last section in this chapter, “Multibyte Strings and Character Sets,” explains
                  the different character sets and the functions to convert and handle different
                  ones, including multi-byte strings used in Asian languages.
                        Chapter 10, “Using PEAR,” introduces PEAR, the PHP Extension and
                  Application Repository. Starting with concepts and installation, the chapter
                  shows how to use PEAR and maintain the local installed packages. This chap-
                  ter also includes a tour of the PEAR web site.
                        Chapter 11, “Important PEAR Packages,” gives an overview of the most
                  important PEAR packages, along with examples. Packages covered include
                  Template Systems, the Auth package to do authentication, form handling
                  with the HTML_QuickForm package, and a package used to simplify caching.
                        Chapter 12, “Building PEAR Components,” explains how to create your
                  own PEAR package. The PEAR Coding Standard and package.xml package def-
                  inition format, together with tips on including files and package layout, get
                  you on your way to completing your first PEAR package.
                        Chapter 13, “Making the Move,” deals with the few backward-incompatible
                  changes that were introduced between PHP 4 and PHP 5. This chapter tells you
                  which things you need to take care of when making your application work on PHP
                  5, and provides workarounds wherever possible.
                        Chapter 14, “Performance,” shows you how to make your scripts perform
                  better. The chapter offers tips on standard PHP usage, the use of external util-
                  ities (APD and Xdebug) to find problems in your scripts, and PHP accelerators
                  like APC and Zend Performance Suite.
Gutmans_PrefaceFore Page xxvii Thursday, September 23, 2004 9:06 AM




            A Note About Coding Styles                                                           xxvii


                            Chapter 15, “An Introduction to Writing PHP Extensions,” explains how
                      to write your own custom PHP extension. We use a simple example to explain
                      the most important things like parameter parsing and resource management.
                            Chapter 16, “PHP Shell Scripting,” shows you how to write shell scripts
                      in PHP, because PHP is useful for more than just web applications. We care-
                      fully explain the differences between the CLI and CGI executables in which
                      PHP comes, including command-line parameter parsing and process control.
                            This book also includes three appendices. Appendix A, “PEAR and PECL
                      Package Index,” provides an overview of all important packages, with descrip-
                      tions and dependencies on other packages. Appendix B, “phpDocument Format
                      Reference,” explains the syntax as understood by the PHP Documenter tool to
                      generate API documentation from source code. Appendix C, “Zend Studio
                      Quick Start,” is an introduction to working in the Zend Studio IDE.


                      A NOTE ABOUT CODING STYLES
                      There are almost as many coding styles as there are programmers. The PHP
                      examples in this book follow the PEAR coding standard, with the opening
                      curly bracket on the line below the function name. In some cases, we’ve placed
                      the curly bracket on the same line as the function name. We encourage you to
                      adopt the style you are most comfortable with.

                         Note: A code continuation character, ➥, appears at the beginning of code
                      lines that have wrapped down from the line above it.


                      ABOUT THE SOFTWARE
                      Included in the back of this book is a special link to Zend.com, where you can
                      download a fully functional, 90-day trial version of the Zend Studio IDE. Be
                      sure to use the license key printed on the inside back cover of this book when
                      you install Zend Studio.
                           The Zend Development Environment (ZDE) is a convenient tool that
                      integrates an editor, debugger, and project manager to help you develop, man-
                      age, and debug your code. It can connect to your own installed server or
                      directly to the Zend Studio server component. It is a powerful tool that allows
                      you to debug your code in its natural environment.


                      UPDATES AND ERRATA AND DOWNLOADS
                      Updates, errata, and copies of the sample programs used in this book can be
                      found at the following URL: http//php5powerprogramming.com. We encourage
                      you to visit this site.
Gutmans_PrefaceFore Page xxviii Thursday, September 23, 2004 9:06 AM




       xxviii                                                                               Preface



                  ACKNOWLEDGEMENTS
                  This book could not have been written without feedback from our technical
                  reviewers; therefore, we would like to thank Marcus Börger, Steph Fox, Martin
                  Jansen, and Rob Richards for their excellent comments and feedback. Besides
                  these four reviewers, there are a few more people who helped answer several
                  questions during the writing of this book, more specifically Christian Stocker for
                  helping with the XML chapter, Wez Furlong and Sara Golemon for answering
                  questions about the streams layer, Pierre-Alain Joye for providing some insights
                  in the inner workings of the GD library, and less specifically the PEAR commu-
                  nity for their support and dedication to a great repository of usable PEAR com-
                  ponents. Some sections in this book were contributed by co-authors; Georg
                  Richter contributed the MySQLi section of the database chapter, and Zeev
                  Suraski added the section on Zend's Performance Suite.
                        We would also like to thank Mark L. Taub and the editorial team of Pear-
                  son PTR for the things they are good at doing: organizing, planning, and mar-
                  keting this book, and making sure everything fits together. Thanks to Janet
                  Valade, for helpful developmental editing support, and our project editor
                  Kristy Hart, who helped us wrap up the book under pressure and put the final
                  touches on it.

                  Enjoy!
                  Andi, Stig, and Derick
Gutmans_Ch01 Page 1 Thursday, September 23, 2004 2:35 PM




                                                                  C   H   A   P   T   E   R       1

          What Is New in PHP 5?
          “The best way to be ready for the future is to invent it.”— John Sculley




              1.1 INTRODUCTION
                     Only time will tell if the PHP 5 release will be as successful as its two prede-
                     cessors (PHP 3 and PHP 4). The new features and changes aim to rid PHP of
                     any weaknesses it may have had and make sure that it stays in the lead as the
                     world’s best web-scripting language.
                          This book details PHP 5 and its new features. However, if you are familiar
                     with PHP 4 and are eager to know what is new in PHP 5, this chapter is for you.
                          When you finish reading this chapter, you will have learned

                        ☞ The new language features
                        ☞ News concerning PHP extensions
                        ☞ Other noteworthy changes to PHP’s latest version



              1.2 LANGUAGE FEATURES

                     1.2.1 New Object-Oriented Model
                     When Zeev Suraski added the object-oriented syntax back in the days of PHP
                     3, it was added as “syntactic sugar for accessing collections.” The OO model
                     also had support for inheritance and allowed a class (and object) to aggregate
                     both methods and properties, but not much more. When Zeev and Andi Gut-
                     mans rewrote the scripting engine for PHP 4, it was a completely new engine;
                     it ran much faster, was more stable, and boasted more features. However, the
                     OO model first introduced in PHP 3 was barely touched.
                           Although the object model had serious limitations, it was used exten-
                     sively around the world, often in large PHP applications. This impressive use
                     of the OOP paradigm with PHP 4, despite its weaknesses, led to it being the
                     main focus for the PHP 5 release.


                                                                                                   1
Gutmans_Ch01 Page 2 Thursday, September 23, 2004 2:35 PM




       2                                                                What Is New in PHP 5? Chap. 1


                       So, what were some of the limitations in PHP 3 and 4? The biggest limi-
                  tation (which led to further limitations) was the fact that the copy semantics of
                  objects were the same as for native types. So, how did this actually affect the
                  PHP developer? When assigning a variable (that points to an object) to
                  another variable, a copy of the object would be created. Not only did this
                  impact performance, but it also usually led to obscure behavior and bugs in
                  PHP 4 applications because many developers thought that both variables
                  would point at the same object, which was not the case. The variables were
                  instead pointing at separate copies of the same object. Changing one would
                  not change the other.
                       For example:
                         class Person {
                             var $name;
                             function getName()
                             {
                                 return $this->name;
                             }
                             function setName($name)
                             {
                                 $this->name = $name;
                             }
                             function Person($name)
                             {
                                 $this->setName($name);
                             }
                         }

                         function changeName($person, $name)
                         {
                             $person->setName($name);
                         }

                         $person = new Person("Andi");
                         changeName($person, "Stig");
                         print $person->getName();

                       In PHP 4, this code would print out "Andi". The reason is that we pass
                  the object $person to the changeName() function by-value, and thus, $person is
                  copied and changeName() works on a copy of $person.
                       This behavior is not intuitive, as many developers would expect the Java-
                  like behavior. In Java, variables actually hold a handle (or pointer) to the
                  object, and therefore, when it is copied, only the handle (and not the entire
                  object) is duplicated.
                       There were two kinds of users in PHP 4: the ones who were aware of this
                  problem and the ones who were not. The latter would usually not notice this
                  problem and their code was written in a way where it did not really matter if
                  the problem existed. Surely some of these people had sleepless nights trying to
                  track down weird bugs that they could not pinpoint. The former group dealt
                  with this problem by always passing and assigning objects by reference. This
                  would prevent the engine from copying their objects, but it would be a head-
                  ache because the code included numerous & signs.
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5
Thourough guid to PHP5

Weitere ähnliche Inhalte

Ähnlich wie Thourough guid to PHP5

PHP 5.4 - Begin your love affair with traits
PHP 5.4 - Begin your love affair with traitsPHP 5.4 - Begin your love affair with traits
PHP 5.4 - Begin your love affair with traitsGraham Weldon
 
P Hundamental Security Coding Secure With Php Lamp
P Hundamental Security Coding Secure With Php LampP Hundamental Security Coding Secure With Php Lamp
P Hundamental Security Coding Secure With Php Lampphptechtalk
 
PHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdfPHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdfchristiemarie4
 
The PHP Anthology
The PHP AnthologyThe PHP Anthology
The PHP Anthologygywbd
 
2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida realPHP Conference Argentina
 
Perl Myths 200909
Perl Myths 200909Perl Myths 200909
Perl Myths 200909Tim Bunce
 
PHP - History, Introduction, Summary, Extensions and Frameworks
PHP - History, Introduction, Summary, Extensions and FrameworksPHP - History, Introduction, Summary, Extensions and Frameworks
PHP - History, Introduction, Summary, Extensions and FrameworksRoyston Olivera
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1ADARSH BHATT
 
Around the PHP Community
Around the PHP CommunityAround the PHP Community
Around the PHP CommunityBen Ramsey
 
Python Intro For Managers
Python Intro For ManagersPython Intro For Managers
Python Intro For ManagersAtul Shridhar
 
PHP - Programming language war, does it matter
PHP - Programming language war, does it matterPHP - Programming language war, does it matter
PHP - Programming language war, does it matterMizno Kruge
 
Why should I learn python
Why should I learn pythonWhy should I learn python
Why should I learn pythongrinu
 
YAPC::EU::2009 - How Opera Software uses Perl
YAPC::EU::2009 - How Opera Software uses PerlYAPC::EU::2009 - How Opera Software uses Perl
YAPC::EU::2009 - How Opera Software uses PerlCosimo Streppone
 

Ähnlich wie Thourough guid to PHP5 (20)

php_mysql_tutorial
php_mysql_tutorialphp_mysql_tutorial
php_mysql_tutorial
 
php_mysql_tutorial
php_mysql_tutorialphp_mysql_tutorial
php_mysql_tutorial
 
PHP 5.4 - Begin your love affair with traits
PHP 5.4 - Begin your love affair with traitsPHP 5.4 - Begin your love affair with traits
PHP 5.4 - Begin your love affair with traits
 
P Hundamental Security Coding Secure With Php Lamp
P Hundamental Security Coding Secure With Php LampP Hundamental Security Coding Secure With Php Lamp
P Hundamental Security Coding Secure With Php Lamp
 
PHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdfPHP vs Python Which is Best for Web Development.pdf
PHP vs Python Which is Best for Web Development.pdf
 
The PHP Anthology
The PHP AnthologyThe PHP Anthology
The PHP Anthology
 
Handson Python
Handson PythonHandson Python
Handson Python
 
core python.pdf
core python.pdfcore python.pdf
core python.pdf
 
2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real2013 - Dustin whittle - Escalando PHP en la vida real
2013 - Dustin whittle - Escalando PHP en la vida real
 
PHP
PHPPHP
PHP
 
Perl Myths 200909
Perl Myths 200909Perl Myths 200909
Perl Myths 200909
 
Python3handson
Python3handsonPython3handson
Python3handson
 
PHP - History, Introduction, Summary, Extensions and Frameworks
PHP - History, Introduction, Summary, Extensions and FrameworksPHP - History, Introduction, Summary, Extensions and Frameworks
PHP - History, Introduction, Summary, Extensions and Frameworks
 
PHP Web Development
PHP Web DevelopmentPHP Web Development
PHP Web Development
 
Learn PHP Lacture1
Learn PHP Lacture1Learn PHP Lacture1
Learn PHP Lacture1
 
Around the PHP Community
Around the PHP CommunityAround the PHP Community
Around the PHP Community
 
Python Intro For Managers
Python Intro For ManagersPython Intro For Managers
Python Intro For Managers
 
PHP - Programming language war, does it matter
PHP - Programming language war, does it matterPHP - Programming language war, does it matter
PHP - Programming language war, does it matter
 
Why should I learn python
Why should I learn pythonWhy should I learn python
Why should I learn python
 
YAPC::EU::2009 - How Opera Software uses Perl
YAPC::EU::2009 - How Opera Software uses PerlYAPC::EU::2009 - How Opera Software uses Perl
YAPC::EU::2009 - How Opera Software uses Perl
 

Thourough guid to PHP5

  • 1. Gutmans_Frontmatter Page i Thursday, September 23, 2004 9:05 AM PHP 5 Power Programming
  • 2. Gutmans_Frontmatter Page ii 1 Wednesday, September 15, 9:05 AM perens_series_7x9.25.fm Page Thursday, September 23, 20042004 10:54 AM BRUCE PERENS’ OPEN SOURCE SERIES http://www.phptr.com/perens ◆ Java Application Development on Linux Carl Albing and Michael Schwarz ◆ C++ GUI Programming with Qt 3 Jasmin Blanchette, Mark Summerfield ◆ Managing Linux Systems with Webmin: System Administration and Module Development Jamie Cameron ◆ Understanding the Linux Virtual Memory Manager Mel Gorman ◆ Implementing CIFS: The Common Internet File System Christopher Hertel ◆ Embedded Software Development with eCos Anthony Massa ◆ Rapid Application Development with Mozilla Nigel McFarlane ◆ The Linux Development Platform: Configuring, Using, and Maintaining a Complete Programming Environment Rafeeq Ur Rehman, Christopher Paul ◆ Intrusion Detection with SNORT: Advanced IDS Techniques Using SNORT, Apache, MySQL, PHP, and ACID Rafeeq Ur Rehman ◆ The Official Samba-3 HOWTO and Reference Guide John H. Terpstra, Jelmer R. Vernooij, Editors ◆ Samba-3 by Example: Practical Exercises to Successful Deployment John H. Terpstra
  • 3. Gutmans_Frontmatter Page iii Thursday, September 23, 2004 9:05 AM PHP 5 Power Programming Andi Gutmans, Stig Sæther Bakken, and Derick Rethans PRENTICE HALL Professional Technical Reference Indianapolis, IN 46240 www.phptr.com
  • 4. Gutmans_Frontmatter Page iv Thursday, September 23, 2004 2:14 PM The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for inciden- tal or consequential damages in connection with or arising out of the use of the information or programs con- tained herein. Publisher: John Wait Editor in Chief: Don O’Hagan Acquisitions Editor: Mark L. Taub Editorial Assistant: Noreen Regina Development Editor:Janet Valade Marketing Manager: Robin O'Brien Cover Designer: Nina Scuderi Managing Editor: Gina Kanouse Senior Project Editor: Kristy Hart Copy Editor: Specialized Composition Indexer: Lisa Stumpf Senior Compositor: Gloria Schurick Manufacturing Buyer: Dan Uhrig The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U. S. Corporate and Government Sales (800) 382-3419 corpsales@pearsontechgroup.com For sales outside the U. S., please contact: International Sales international@pearsoned.com Visit us on the Web: www.phptr.com Library of Congress Cataloging-in-Publication Data: 2004107331 Copyright © 2005 Pearson Education, Inc. This material may be distrubuted only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/). Pearson Education, Inc. One Lake Street Upper Saddle River, NJ 07458 Every effort was made to contact and credit all copyright holders. Use of material without proper credit is unintentional. ISBN 0-131-47149-X Text printed in the United States on recycled paper at Phoenix in Hagerstown, Maryland. First printing, [October 2004]
  • 5. Gutmans_Frontmatter Page v Thursday, September 23, 2004 9:05 AM To Ifat, my wife and best friend, who has patiently put up with my involement in PHP from the very beginning, and has encouraged and supported me every step of the way. Andi Gutmans To Marianne, for patience and encouragement. Stig Sæther Bakken To my parents, who care for me even when I’m not around; and to 42, the answer to life, the universe of everything. Derick Rethans
  • 6. Gutmans_Frontmatter Page vi Thursday, September 23, 2004 9:05 AM
  • 7. Gutmans_Frontmatter Page vii Thursday, September 23, 2004 9:05 AM vii Contents Foreword by Zeev Suraski Preface: Introduction and Background Chapter 1: What Is New in PHP 5? Chapter 2: PHP 5 Basic Language Chapter 3: PHP 5 OO Language Chapter 4: PHP 5 Advanced OOP and Design Patterns Chapter 5: How to Write a Web Application with PHP Chapter 6: Databases with PHP 5 Chapter 7: Error Handling Chapter 8: XML with PHP 5 Chapter 9: Mainstream Extensions Chapter 10: Using PEAR Chapter 11: Important PEAR Packages Chapter 12: Building PEAR Components Chapter 13: Making the Move Chapter 14: Performance Chapter 15: An Introduction to Writing PHP Extensions Chapter 16: PHP Shell Scripting A. PEAR and PECL Package Index B. phpDocumentor Format Reference C. Zend Studio Quick Start Index
  • 8. Gutmans_Frontmatter Page viii Thursday, September 23, 2004 9:05 AM
  • 9. Gutmans_TOC Page ix Thursday, September 23, 2004 9:06 AM Contents Foreword............................................................................................................. xxi Preface ................................................................................................................xxii 1 What Is New in PHP 5? ........................................................................................1 1.1 Introduction ........................................................................................................ 1 1.2 Language Features ............................................................................................. 1 1.2.1 New Object-Oriented Model........................................................................ 1 1.2.2 New Object-Oriented Features................................................................... 3 1.2.3 Other New Language Features .................................................................. 7 1.3 General PHP Changes........................................................................................ 8 1.3.1 XML and Web Services ............................................................................... 8 1.4 Other New Features in PHP 5 ......................................................................... 11 1.4.1 New Memory Manager.............................................................................. 11 1.4.2 Dropped Support for Windows 95............................................................. 11 1.5 Summary........................................................................................................... 11 2 PHP 5 Basic Language .......................................................................................13 2.1 Introduction ...................................................................................................... 13 2.2 HTML Embedding ............................................................................................ 14 2.3 Comments ......................................................................................................... 14 2.4 Variables............................................................................................................ 15 2.4.1 Indirect References to Variables .............................................................. 16 2.4.2 Managing Variables .................................................................................. 16 2.4.3 Superglobals .............................................................................................. 18 2.5 Basic Data Types .............................................................................................. 18 2.5.1 Integers ...................................................................................................... 19 2.5.2 Floating-Point Numbers ........................................................................... 19 2.5.3 Strings........................................................................................................ 19 2.5.4 Booleans ..................................................................................................... 22 2.5.5 Null ............................................................................................................ 23 ix
  • 10. Gutmans_TOC Page x Thursday, September 23, 2004 9:06 AM x Contents 2.5.6 Resources ...................................................................................................23 2.5.7 Arrays.........................................................................................................23 2.5.8 Constants ...................................................................................................30 2.6 Operators...........................................................................................................31 2.6.1 Binary Operators .......................................................................................32 2.6.2 Assignment Operators...............................................................................32 2.6.3 Comparison Operators ..............................................................................33 2.6.4 Logical Operators ......................................................................................34 2.6.5 Bitwise Operators ......................................................................................35 2.6.6 Unary Operators........................................................................................36 2.6.7 Negation Operators ...................................................................................36 2.6.8 Increment/Decrement Operators ..............................................................37 2.6.9 The Cast Operators ...................................................................................38 2.6.10 The Silence Operator...............................................................................39 2.6.11 The One and Only Ternary Operator .....................................................39 2.7 Control Structures ............................................................................................39 2.7.1 Conditional Control Structures.................................................................39 2.7.2 Loop Control Structures ............................................................................42 2.7.3 Code Inclusion Control Structures ...........................................................45 2.8 Functions ...........................................................................................................48 2.8.1 User-Defined Functions ............................................................................49 2.8.2 Function Scope...........................................................................................49 2.8.3 Returning Values By Value ......................................................................50 2.8.4 Returning Values By Reference................................................................51 2.8.5 Declaring Function Parameters................................................................52 2.8.6 Static Variables .........................................................................................53 2.9 Summary ...........................................................................................................54 3 PHP 5 OO Language .......................................................................................... 55 3.1 Introduction.......................................................................................................55 3.2 Objects ...............................................................................................................55 3.3 Declaring a Class ..............................................................................................57 3.4 The new Keyword and Constructors ................................................................57 3.5 Destructors ........................................................................................................58 3.6 Accessing Methods and Properties Using the $this Variable.......................59 3.6.1 public, protected, and private Properties .......................................60 3.6.2 public, protected, and private Methods ..........................................61 3.6.3 Static Properties ........................................................................................62 3.6.4 Static Methods ...........................................................................................64 3.7 Class Constants.................................................................................................65 3.8 Cloning Objects .................................................................................................66 3.9 Polymorphism....................................................................................................67 3.10 parent:: and self::........................................................................................70 3.11 instanceof Operator....................................................................................71
  • 11. Gutmans_TOC Page xi Thursday, September 23, 2004 9:06 AM Contents xi 3.12 Abstract Methods and Classes ....................................................................... 72 3.13 Interfaces ........................................................................................................ 73 3.14 Inheritance of Interfaces ................................................................................ 75 3.15 final Methods ............................................................................................... 75 3.16 final Classes ................................................................................................. 76 3.17 __toString() Method.................................................................................. 76 3.18 Exception Handling ........................................................................................ 77 3.19 __autoload() ............................................................................................... 80 3.20 Class Type Hints in Function Parameters .................................................... 82 3.21 Summary......................................................................................................... 83 4 PHP 5 Advanced OOP and Design Patterns .................................................85 4.1 Introduction ...................................................................................................... 85 4.2 Overloading Capabilities.................................................................................. 85 4.2.1 Property and Method Overloading ........................................................... 85 4.2.2 Overloading the Array Access Syntax...................................................... 88 4.3 Iterators ............................................................................................................ 89 4.4 Design Patterns ................................................................................................ 94 4.4.1 Strategy Pattern........................................................................................ 95 4.4.2 Singleton Pattern ...................................................................................... 97 4.4.3 Factory Pattern ......................................................................................... 98 4.4.4 Observer Pattern ..................................................................................... 101 4.5 Reflection......................................................................................................... 103 4.5.1 Introduction ............................................................................................. 103 4.5.2 Reflection API.......................................................................................... 103 4.5.3 Reflection Examples................................................................................ 106 4.5.4 Implementing the Delegation Pattern Using Reflection....................... 107 4.6 Summary......................................................................................................... 109 5 How to Write a Web Application with PHP.................................................111 5.1 Introduction .................................................................................................... 111 5.2 Embedding into HTML .................................................................................. 112 5.3 User Input ....................................................................................................... 114 5.4 Safe-Handling User Input.............................................................................. 117 5.4.1 Common Mistakes ................................................................................... 117 5.5 Techniques to Make Scripts “Safe” ................................................................ 120 5.5.1 Input Validation ...................................................................................... 120 5.5.2 HMAC Verification.................................................................................. 122 5.5.3 PEAR::Crypt_HMAC............................................................................... 124 5.5.4 Input Filter .............................................................................................. 127 5.5.5 Working with Passwords ........................................................................ 127 5.5.6 Error Handling ........................................................................................ 129 5.6 Cookies ............................................................................................................ 131 5.7 Sessions ........................................................................................................... 134
  • 12. Gutmans_TOC Page xii Thursday, September 23, 2004 9:06 AM xii Contents 5.8 File Uploads ....................................................................................................137 5.8.1 Handling the Incoming Uploaded File ...................................................138 5.9 Architecture.....................................................................................................143 5.9.1 One Script Serves All ..............................................................................143 5.9.2 One Script per Function ..........................................................................144 5.9.3 Separating Logic from Layout ................................................................144 5.10 Summary .......................................................................................................146 6 Databases with PHP 5 ..................................................................................... 149 6.1 Introduction.....................................................................................................149 6.2 MySQL.............................................................................................................149 6.2.1 MySQL Strengths and Weaknesses .......................................................150 6.2.2 PHP Interface ..........................................................................................150 6.2.3 Example Data ..........................................................................................151 6.2.4 Connections..............................................................................................151 6.2.5 Buffered Versus Unbuffered Queries .....................................................153 6.2.6 Queries .....................................................................................................154 6.2.7 Multi Statements.....................................................................................155 6.2.8 Fetching Modes........................................................................................156 6.2.9 Prepared Statements...............................................................................156 6.2.10 BLOB Handling .....................................................................................158 6.3 SQLite..............................................................................................................160 6.3.1 SQLite Strengths and Weaknesses ........................................................160 6.3.2 Best Areas of Use.....................................................................................161 6.3.3 PHP Interface ..........................................................................................162 6.4 PEAR DB .........................................................................................................176 6.4.1 Obtaining PEAR DB................................................................................176 6.4.2 Pros and Cons of Database Abstraction .................................................177 6.4.3 Which Features Are Abstracted? ............................................................177 6.4.4 Database Connections .............................................................................178 6.4.5 Executing Queries ...................................................................................180 6.4.6 Fetching Results ......................................................................................182 6.4.7 Sequences .................................................................................................184 6.4.8 Portability Features ................................................................................185 6.4.9 Abstracted Errors ....................................................................................186 6.4.10 Convenience Methods............................................................................188 6.5 Summary .........................................................................................................190 7 Error Handling.................................................................................................. 191 7.1 Introduction.....................................................................................................191 7.2 Types of Errors ................................................................................................192 7.2.1 Programming Errors ...............................................................................192 7.2.2 Undefined Symbols..................................................................................194 7.2.3 Portability Errors ....................................................................................197
  • 13. Gutmans_TOC Page xiii Thursday, September 23, 2004 9:06 AM Contents xiii 7.2.4 Runtime Errors........................................................................................ 201 7.2.5 PHP Errors .............................................................................................. 201 7.3 PEAR Errors ................................................................................................... 206 7.3.1 The PEAR_Error Class ........................................................................... 209 7.3.2 Handling PEAR Errors ........................................................................... 212 7.3.3 PEAR Error Modes.................................................................................. 213 7.3.4 Graceful Handling ................................................................................... 213 7.4 Exceptions ....................................................................................................... 216 7.4.1 What Are Exceptions? ............................................................................. 216 7.4.2 try, catch, and throw ............................................................................... 216 7.5 Summary......................................................................................................... 218 8 XML with PHP 5 ................................................................................................219 8.1 Introduction .................................................................................................... 219 8.2 Vocabulary....................................................................................................... 220 8.3 Parsing XML ................................................................................................... 222 8.3.1 SAX .......................................................................................................... 222 8.3.2 DOM ......................................................................................................... 226 8.4 SimpleXML ..................................................................................................... 231 8.4.1 Creating a SimpleXML Object................................................................ 232 8.4.2 Browsing SimpleXML Objects ................................................................ 233 8.4.3 Storing SimpleXML Objects ................................................................... 234 8.5 PEAR ............................................................................................................... 234 8.5.1 XML_Tree ................................................................................................ 235 8.5.2 XML_RSS................................................................................................. 236 8.6 Converting XML ............................................................................................. 239 8.6.1 XSLT ........................................................................................................ 239 8.7 Communicating with XML............................................................................. 244 8.7.1 XML-RPC................................................................................................. 244 8.7.2 SOAP........................................................................................................ 252 8.8 Summary......................................................................................................... 259 9 Mainstream Extensions ...................................................................................261 9.1 Introduction .................................................................................................... 261 9.2 Files and Streams ........................................................................................... 261 9.2.1 File Access ............................................................................................... 262 9.2.2 Program Input/Output ............................................................................ 264 9.2.3 Input/Output Streams............................................................................. 267 9.2.4 Compression Streams ............................................................................. 268 9.2.5 User Streams ........................................................................................... 270 9.2.6 URL Streams ........................................................................................... 271 9.2.7 Locking .................................................................................................... 276 9.2.8 Renaming and Removing Files............................................................... 277 9.2.9 Temporary Files ...................................................................................... 278
  • 14. Gutmans_TOC Page xiv Thursday, September 23, 2004 9:06 AM xiv Contents 9.3 Regular Expressions .......................................................................................279 9.3.1 Syntax ......................................................................................................279 9.3.2 Functions..................................................................................................293 9.4 Date Handling .................................................................................................301 9.4.1 Retrieving Date and Time Information ..................................................301 9.4.2 Formatting Date and Time .....................................................................305 9.4.3 Parsing Date Formats .............................................................................313 9.5 Graphics Manipulation with GD....................................................................314 9.5.1 Case 1: Bot-Proof Submission Forms .....................................................315 9.5.2 Case 2: Bar Chart ....................................................................................320 9.5.3 Exif..........................................................................................................326 9.6 Multi-Byte Strings and Character Sets .........................................................329 9.6.1 Character Set Conversions......................................................................330 9.6.2 Extra Functions Dealing with Multi-Byte Character Sets ...................335 9.6.3 Locales......................................................................................................340 9.7 Summary .........................................................................................................343 10 Using PEAR........................................................................................................ 345 10.1 Introduction...................................................................................................345 10.2 PEAR Concepts .............................................................................................346 10.2.1 Packages.................................................................................................346 10.2.2 Releases..................................................................................................346 10.2.3 Version Numbers ...................................................................................347 10.3 Obtaining PEAR............................................................................................349 10.3.1 Installing with UNIX / Linux PHP Distribution .................................350 10.3.2 Installing with PHP Windows Installer ...............................................351 10.3.3 go-pear.org .............................................................................................351 10.4 Installing Packages .......................................................................................354 10.4.1 Using the pear Command ...................................................................354 10.5 Configuration Parameters ............................................................................358 10.6 PEAR Commands..........................................................................................364 10.6.1 pear install ......................................................................................364 10.6.2 pear list .............................................................................................368 10.6.3 pear info .............................................................................................369 10.6.4 pear list-all ....................................................................................370 10.6.5 pear list-upgrades .........................................................................370 10.6.6 pear upgrade ......................................................................................371 10.6.7 pear upgrade-all..............................................................................372 10.6.8 pear uninstall ..................................................................................373 10.6.9 pear search ........................................................................................373 10.6.10 pear remote-list............................................................................374 10.6.11 pear remote-info............................................................................375 10.6.12 pear download ..................................................................................375 10.6.13 pear config-get ..............................................................................376
  • 15. Gutmans_TOC Page xv Thursday, September 23, 2004 9:06 AM Contents xv 10.6.14 pear config-set ............................................................................. 376 10.6.15 pear config-show ........................................................................... 376 10.6.16 Shortcuts.............................................................................................. 377 10.7 Installer Front-Ends..................................................................................... 378 10.7.1 CLI (Command Line Interface) Installer ............................................. 378 10.7.2 Gtk Installer .......................................................................................... 378 10.8 Summary....................................................................................................... 381 11 Important PEAR Packages .............................................................................383 11.1 Introduction .................................................................................................. 383 11.2 Database Queries.......................................................................................... 383 11.3 Template Systems......................................................................................... 383 11.3.1 Template Terminology .......................................................................... 384 11.3.2 HTML_Template_IT ............................................................................. 384 11.3.3 HTML_Template_Flexy ....................................................................... 387 11.4 Authentication .............................................................................................. 392 11.4.1 Overview ................................................................................................ 392 11.4.2 Example: Auth with Password File...................................................... 393 11.4.3 Example: Auth with DB and User Data .............................................. 394 11.4.4 Auth Security Considerations............................................................... 396 11.4.5 Auth Scalability Considerations........................................................... 397 11.4.6 Auth Summary ...................................................................................... 398 11.5 Form Handling.............................................................................................. 398 11.5.1 HTML_QuickForm.................................................................................. 398 11.5.2 Example: Login Form............................................................................ 399 11.5.3 Receiving Data....................................................................................... 399 11.6 Caching.......................................................................................................... 399 11.6.1 Cache_Lite .......................................................................................... 399 11.7 Summary....................................................................................................... 401 12 Building PEAR Components ..........................................................................403 12.1 Introduction .................................................................................................. 403 12.2 PEAR Standards........................................................................................... 403 12.2.1 Symbol Naming ..................................................................................... 403 12.2.2 Indentation ............................................................................................ 406 12.3 Release Versioning........................................................................................ 408 12.4 CLI Environment.......................................................................................... 408 12.5 Fundamentals ............................................................................................... 410 12.5.1 When and How to Include Files............................................................ 410 12.5.2 Error Handling ...................................................................................... 411 12.6 Building Packages ........................................................................................ 411 12.6.1 PEAR Example: HelloWorld ................................................................. 411 12.6.2 Building the Tarball.............................................................................. 414 12.6.3 Verification ............................................................................................ 414 12.6.4 Regression Tests.................................................................................... 416
  • 16. Gutmans_TOC Page xvi Thursday, September 23, 2004 9:06 AM xvi Contents 12.7 The package.xml Format ..............................................................................416 12.7.1 Package Information .............................................................................417 12.7.2 Release Information ..............................................................................419 12.8 Dependencies.................................................................................................423 12.8.1 Element: <deps> ...................................................................................423 12.8.2 Element: <dep> .....................................................................................423 12.8.3 Dependency Types .................................................................................424 12.8.4 Reasons to Avoid Dependencies............................................................425 12.8.5 Optional Dependencies..........................................................................426 12.8.6 Some Examples......................................................................................426 12.9 String Substitutions......................................................................................427 12.9.1 Element: <replace> .............................................................................427 12.9.2 Examples................................................................................................427 12.10 Including C Code.........................................................................................428 12.10.1 Element: <configureoptions> .......................................................428 12.10.2 Element: <configureoption> .........................................................428 12.11 Releasing Packages .....................................................................................428 12.12 The PEAR Release Process.........................................................................429 12.13 Packaging ....................................................................................................430 12.13.1 Source Analysis....................................................................................430 12.13.2 MD5 Checksum Generation ................................................................430 12.13.3 Package.xml Update............................................................................431 12.13.4 Tarball Creation ..................................................................................431 12.14 Uploading ....................................................................................................432 12.14.1 Upload Release ....................................................................................432 12.14.2 Finished!...............................................................................................432 12.15 Summary .....................................................................................................432 13 Making the Move .............................................................................................. 433 13.1 Introduction...................................................................................................433 13.2 The Object Model ..........................................................................................433 13.3 Passing Objects to Functions........................................................................433 13.4 Compatibility Mode.......................................................................................435 13.4.1 Casting Objects ......................................................................................435 13.4.2 Comparing Objects ................................................................................436 13.5 Other Changes ..............................................................................................437 13.5.1 Assigning to $this ................................................................................437 13.5.2 get_class .............................................................................................440 13.6 E_STRICT ......................................................................................................441 13.6.1 Automagically Creating Objects ...........................................................441 13.6.2 var and public ....................................................................................441 13.6.3 Constructors...........................................................................................442 13.6.4 Inherited Methods .................................................................................442 13.6.5 Define Classes Before Usage.................................................................443
  • 17. Gutmans_TOC Page xvii Thursday, September 23, 2004 9:06 AM Contents xvii 13.7 Other Compatibility Problems ..................................................................... 443 13.7.1 Command-Line Interface ...................................................................... 443 13.7.2 Comment Tokens................................................................................... 443 13.7.3 MySQL ................................................................................................... 445 13.8 Changes in Functions ................................................................................... 445 13.8.1 array_merge() .................................................................................... 445 13.8.2 strrpos() and strripos()............................................................... 446 13.9 Summary....................................................................................................... 447 14 Performance .......................................................................................................449 14.1 Introduction .................................................................................................. 449 14.2 Design for Performance ................................................................................ 449 14.2.1 PHP Design Tip #1: Beware of State ................................................... 450 14.2.2 PHP Design Tip #2: Cache!................................................................... 451 14.2.3 PHP Design Tip #3: Do Not Over Design!............................................ 456 14.3 Benchmarking............................................................................................... 457 14.3.1 Using ApacheBench .............................................................................. 457 14.3.2 Using Siege ............................................................................................ 458 14.3.3 Testing Versus Real Traffic .................................................................. 459 14.4 Profiling with Zend Studio's Profiler ........................................................... 459 14.5 Profiling with APD........................................................................................ 461 14.5.1 Installing APD....................................................................................... 461 14.5.2 Analyzing Trace Data ........................................................................... 462 14.6 Profiling with Xdebug................................................................................... 465 14.6.1 Installing Xdebug .................................................................................. 466 14.6.2 Tracing Script Execution ...................................................................... 466 14.6.3 Using KCachegrind ............................................................................... 468 14.7 Using APC (Advanced PHP Cache) ............................................................. 470 14.8 Using ZPS (Zend Performance Suite) .......................................................... 470 14.8.1 Automatic Optimization........................................................................ 471 14.8.2 Compiled Code Caching ........................................................................ 472 14.8.3 Dynamic Content Caching .................................................................... 473 14.8.4 Content Compression ............................................................................ 476 14.9 Optimizing Code ........................................................................................... 477 14.9.1 Micro-Benchmarks ................................................................................ 477 14.9.2 Rewrite in C........................................................................................... 479 14.9.3 OO Versus Procedural Code ................................................................. 480 14.10 Summary..................................................................................................... 481 15 An Introduction to Writing PHP Extensions..............................................483 15.1 Introduction .................................................................................................. 483 15.2 Quickstart ..................................................................................................... 484 15.2.1 Memory Management ........................................................................... 489 15.2.2 Returning Values from PHP Functions ............................................... 490 15.2.3 Completing self-concat()................................................................ 490 15.2.4 Summary of Example............................................................................ 492 15.2.5 Wrapping Third-Party Extensions ....................................................... 492
  • 18. Gutmans_TOC Page xviii Thursday, September 23, 2004 9:06 AM xviii Contents 15.2.6 Global Variables ....................................................................................501 15.2.7 Adding Custom INI Directives..............................................................503 15.2.8 Thread-Safe Resource Manager Macros...............................................504 15.3 Summary .......................................................................................................505 16 PHP Shell Scripting ......................................................................................... 507 16.1 Introduction...................................................................................................507 16.2 PHP CLI Shell Scripts ..................................................................................508 16.2.1 How CLI Differs From CGI ...................................................................508 16.2.2 The Shell-Scripting Environment.........................................................510 16.2.3 Parsing Command-Line Options ..........................................................512 16.2.4 Good Practices........................................................................................515 16.2.5 Process Control ......................................................................................516 16.2.6 Examples................................................................................................520 16.3 Summary .......................................................................................................526 A PEAR and PECL Package Index ................................................................... 527 A.1 Authentication ................................................................................................527 A.2 Benchmarking ................................................................................................530 A.3 Caching ...........................................................................................................530 A.4 Configuration ..................................................................................................531 A.5 Console ............................................................................................................531 A.6 Database .........................................................................................................533 A.7 Date and Time ................................................................................................542 A.8 Encryption ......................................................................................................543 A.9 File Formats....................................................................................................545 A.10 File System ...................................................................................................548 A.11 Gtk Components ...........................................................................................550 A.12 HTML............................................................................................................550 A.13 HTTP.............................................................................................................561 A.14 Images ...........................................................................................................563 A.15 Internationalization .....................................................................................566 A.16 Logging..........................................................................................................568 A.17 Mail ...............................................................................................................569 A.18 Math ..............................................................................................................571 A.19 Networking ...................................................................................................574 A.20 Numbers........................................................................................................584 A.21 Payment ........................................................................................................585 A.22 PEAR............................................................................................................587 A.23 PHP ...............................................................................................................588 A.24 Processing .....................................................................................................594 A.25 Science...........................................................................................................594 A.26 Streams .........................................................................................................595 A.27 Structures .....................................................................................................596 A.28 System...........................................................................................................598 A.29 Text................................................................................................................599
  • 19. Gutmans_TOC Page xix Thursday, September 23, 2004 9:06 AM Contents xix A.30 Tools and Utilities ........................................................................................ 600 A.31 Web Services................................................................................................. 603 A.32 XML .............................................................................................................. 604 B phpDocumentor Format Reference ..............................................................613 B.1 Introduction .................................................................................................... 613 B.2 Documentation Comments ............................................................................ 613 B.3 Tag Reference ................................................................................................. 615 B.3.1 abstract ................................................................................................ 615 B.3.2 access .................................................................................................... 616 B.3.3 author .................................................................................................... 617 B.3.4 category ................................................................................................ 618 B.3.5 copyright.............................................................................................. 618 B.3.6 deprecated............................................................................................ 618 B.3.7 example .................................................................................................. 619 B.3.8 filesource............................................................................................ 620 B.3.9 final ...................................................................................................... 620 B.3.10 global ................................................................................................ 621 B.3.11 ignore ................................................................................................ 622 B.3.12 inheritdoc (inline) .......................................................................... 622 B.3.13 internal, internal (inline) ........................................................ 622 B.3.14 licence .............................................................................................. 623 B.3.15 link .................................................................................................... 623 B.3.16 link (inline) ...................................................................................... 623 B.3.17 name .................................................................................................... 624 B.3.18 package .............................................................................................. 624 B.3.19 param .................................................................................................. 626 B.3.20 return ................................................................................................ 627 B.3.21 see........................................................................................................ 627 B.3.22 since .................................................................................................. 628 B.3.23 static ................................................................................................. 628 B.3.24 staticvar........................................................................................... 629 B.3.25 subpackage......................................................................................... 629 B.3.26 todo...................................................................................................... 630 B.3.27 uses .................................................................................................... 630 B.3.28 var........................................................................................................ 631 B.3.29 version ............................................................................................... 631 B.4 Tag Table......................................................................................................... 632 B.5 Using the phpDocumentor Tool ..................................................................... 633 C Zend Studio Quick Start Guide ....................................................................643 C.1 Version 3.5.x ................................................................................................... 643 C.2 About the Zend Studio Client Quick Start Guide......................................... 643 C.3 About Zend ..................................................................................................... 643 C.4 Zend Studio Client: Overview........................................................................ 644
  • 20. Gutmans_TOC Page xx Thursday, September 23, 2004 9:06 AM xx Contents C.4.1 Studio Components .................................................................................644 C.4.2 Client Server Configuration ...................................................................645 C.4.3 Installation and Registration .................................................................645 C.5 Editing a File ..................................................................................................647 C.5.1 Editing a File...........................................................................................647 C.6 Working with Projects ....................................................................................648 C.6.1 Advantages of Working with Projects....................................................648 C.6.2 How to Create a Project ..........................................................................648 C.7 Running the Debugger ..................................................................................648 C.7.1 Internal Debugger...................................................................................649 C.7.2 Remote Debugger ....................................................................................649 C.7.3 Debug URL ..............................................................................................650 C.8 Configure Studio Server for Remote Debugger and Profiling ......................650 C.9 Running the Profiler.......................................................................................651 C.10 Product Support............................................................................................652 C.10.1 Getting Support.....................................................................................653 C.11 Main Features...............................................................................................653 Index.................................................................................................................... 655
  • 21. Gutmans_PrefaceFore Page xxi Thursday, September 23, 2004 9:06 AM Foreword Within the last few years, PHP has grown to be the most widespread web plat- form in the world, operational in more than a third of the web servers across the globe. PHP's growth is not only quantitative but also qualitative. More and more companies, including Fortune companies, rely on PHP to run their busi- ness-critical applications, which creates new jobs and increases the demand for PHP developers. Version 5, due to be released in the very near future, holds an even greater promise. While the complexity of starting off with PHP remains unchanged and very low, the features offered by PHP today enable developers to reach far beyond simple HTML applications. The revised object model allows for large- scale projects to be written efficiently, using standard object-oriented method- ologies. New XML support makes PHP the best language available for pro- cessing XML and, coupled with new SOAP support, an ideal platform for creating and using Web Services. This book, written by my colleague, Andi Gutmans, and two very promi- nent PHP developers, Stig Bakken and Derick Rethans, holds the key to unlocking the riches of PHP 5. It thoroughly covers all of the features of the new version, and is a must-have for all PHP developers who are interested in exploring PHP 5's advanced features. Zeev Suraski xxi
  • 22. Gutmans_PrefaceFore Page xxii Thursday, September 23, 2004 9:06 AM xxii Preface Preface “The best security against revolution is in constant correction of abuses and the introduction of needed improvements. It is the neglect of timely repair that makes rebuilding necessary.”—Richard Whately IN THE BEGINNING It was eight years ago, when Rasmus Lerdorf first started developing PHP/FI. He could not have imagined that his creation would eventually lead to the development of PHP as we know it today, which is being used by millions of people. The first version of “PHP/FI,” called Personal Homepage Tools/ Form Interpreter, was a collection of Perl scripts in 1995.1 One of the basic features was a Perl-like language for handling form submissions, but it lacked many common useful language features, such as for loops. 1 http://groups.google.com/groups?selm=3r7pgp$aa1@ionews.io.org.
  • 23. Gutmans_PrefaceFore Page xxiii Thursday, September 23, 2004 9:06 AM In the Beginning xxiii PHP/FI 2 A rewrite came with PHP/FI 22 in 1997, but at that time the development was almost solely handled by Rasmus. After its release in November of that year, Andi Gutmans and Zeev Suraski bumped into PHP/FI while looking for a lan- guage to develop an e-commerce solution as a university project. They discov- ered that PHP/FI was not quite as powerful as it seemed, and its language was lacking many common features. One of the most interesting aspects included the way while loops were implemented. The hand-crafted lexical scanner would go through the script and when it hit the while keyword it would remember its position in the file. At the end of the loop, the file pointer sought back to the saved position, and the whole loop was reread and re-executed. PHP 3 Zeev and Andi decided to completely rewrite the scripting language. They then teamed up with Rasmus to release PHP 3, and along also came a new name: PHP: Hypertext Preprocessor, to emphasize that PHP was a different product and not only suitable for personal use. Zeev and Andi had also designed and implemented a new extension API. This new API made it possible to easily support additional extensions for performing tasks such as accessing databases, spell checkers and other technologies, which attracted many developers who were not part of the “core” group to join and contribute to the PHP project. At the time of PHP 3’s release3 in June 1998, the estimated PHP installed base consisted of about 50,000 domains. PHP 3 sparked the beginning of PHP’s real breakthrough, and was the first version to have an installed base of more than one million domains. PHP 4 In late 1998, Zeev and Andi looked back at their work in PHP 3 and felt they could have written the scripting language even better, so they started yet another rewrite. While PHP 3 still continuously parsed the scripts while execut- ing them, PHP 4 came with a new paradigm of “compile first, execute later.” The compilation step does not compile PHP scripts into machine code; it instead compiles them into byte code, which is then executed by the Zend Engine (Zend stands for Zeev & Andi), the new heart of PHP 4. Because of this new way of executing scripts, the performance of PHP 4 was much better than that of PHP 3, with only a small amount of backward compatibility breakage4. Among other improvements was an improved extension API for better run-time performance, a web server abstraction layer allowing PHP 4 to run on most pop- ular web servers, and lots more. PHP 4 was officially released on May 22, 2002, and today its installed base has surpassed 15 million domains. 2 http://groups.google.com/groups?selm=Dn1JM9.61t%40gpu.utcc.utoronto.ca. 3 http://groups.google.com/groups?selm=Pine.WNT.3.96.980606130654.-317675I- 100000%40shell.lerdorf.on.ca. 4 http://www.php.net/manual/en/migration4.php.
  • 24. Gutmans_PrefaceFore Page xxiv Thursday, September 23, 2004 9:06 AM xxiv Preface In PHP 3, the minor version number (the middle digit) was never used, and all versions were numbered as 3.0.x. This changed in PHP 4, and the minor version number was used to denote important changes in the language. The first important change came in PHP 4.1.0,5 which introduced superglobals such as $_GET and $_POST. Superglobals can be accessed from within functions without having to use the global keyword. This feature was added in order to allow the register_globals INI option to be turned off. register_globals is a feature in PHP which automatically converts input variables like "?foo=bar" in http:// php.net/?foo=bar to a PHP variable called $foo. Because many people do not check input variables properly, many applications had security holes, which made it quite easy to circumvent security and authentication code. With the new superglobals in place, on April 22, 2002, PHP 4.2.0 was released with the register_globals turned off by default. PHP 4.3.0, the last significant PHP 4 version, was released on December 27, 2002. This version introduced the Command Line Interface (CLI), a revamped file and net- work I/O layer (called streams), and a bundled GD library. Although most of those additions have no real effect on end users, the major version was bumped due to the major changes in PHP’s core. PHP 5 Soon after, the demand for more common object-oriented features increased immensely, and Andi came up with the idea of rewriting the objected-oriented part of the Zend Engine. Zeev and Andi wrote the “Zend Engine II: Feature Overview and Design” document6 and jumpstarted heated discussions about PHP’s future. Although the basic language has stayed the same, many fea- tures were added, dropped, and changed by the time PHP 5 matured. For example, namespaces and multiple inheritance, which were mentioned in the original document, never made it into PHP 5. Multiple inheritance was dropped in favor of interfaces, and namespaces were dropped completely. You can find a full list of new features in Chapter, “What Is New in PHP 5?” PHP 5 is expected to maintain and even increase PHP’s leadership in the web development market. Not only does it revolutionizes PHP’s object- oriented support but it also contains many new features which make it the ultimate web development platform. The rewritten XML functionality in PHP 5 puts it on par with other web technologies in some areas and over- takes them in others, especially due to the new SimpleXML extension which makes it ridiculously easy to manipulate XML documents. In addition, the new SOAP, MySQLi, and variety of other extensions are significant mile- stones in PHP’s support for additional technologies. 5 http://www.php.net/release_4_1_0.php. 6 http://zend.com/engine2/ZendEngine-2.0.pdf.
  • 25. Gutmans_PrefaceFore Page xxv Thursday, September 23, 2004 9:06 AM Audience xxv AUDIENCE This book is an introduction to the advanced features new to PHP 5. It is writ- ten for PHP programmers who are making the move to PHP 5. Although Chapter 2, “PHP 5 Basic Language,” contains an introduction to PHP 5 syn- tax, it is meant as a refresher for PHP programmers and not as a tutorial for new programmers. However, web developers with experience programming other high-level languages may indeed find that this tutorial is all they need in order to begin working effectively with PHP 5. CHAPTER OVERVIEW Chapter 1, “What Is New in PHP 5?” discusses the new features in PHP 5. Most of these new features deal with new object-oriented features, including small examples for each feature. It also gives an overview of the new exten- sions in PHP 5. Most of the topics mentioned in this chapter are explained in more detail in later chapters. Chapter 2, “PHP 5 Basic Language,” introduces the PHP syntax to those readers not familiar with PHP. All basic language constructs and variable types are explained along with simple examples to give the reader the neces- sary building blocks to build real scripts. Chapter 3, “PHP 5 OO Language,” continues exploring PHP 5's syntax, focusing on its object-oriented functionality. This chapter covers basics, such as properties and methods, and progresses to more complicated subjects, such as polymorphism, interfaces, exceptions, and lots more. Using the previous chapter as a foundation, Chapter 4, “PHP 5 Advanced OOP and Design Patterns,” covers some of the most advanced features of PHP 5’s object model. After learning these features, including four commonly used design patterns and PHP’s reflection capabilities, you will soon become an OO wizard. Now that you are familiar with the syntax and language features of PHP, Chapter 5, “How to Write a Web Application with PHP,” introduces you to the world of writing web applications. The authors show you basics, such as han- dling input through form variables and safety techniques, but this chapter also includes more advanced topics, such as handling sessions with cookies and PHP's session extension. You also find a few tips on laying out your source code for your web applications. Chapter 6, “Databases with PHP 5,” introduces using MySQL, SQLite, and Oracle from PHP, but focuses primarily on the PHP 5-specific details of database access. For each database, you learn about some of its strong and weak points, as well as the types of applications at which each excels. And of course, you learn how to interface with them using PHP's native functions or using PEAR DB.
  • 26. Gutmans_PrefaceFore Page xxvi Thursday, September 23, 2004 9:06 AM xxvi Preface All scripts can throw errors, but of course you do not want them to show up on your web site once your application has passed its development state. Chapter 7, “Error Handling,” deals with different types of errors that exist, how to handle those errors with PHP, and how to handle errors with PEAR. As one of the important new features in PHP 5 is its renewed XML sup- port, a chapter on XML features in PHP 5 could not be missed. Chapter 8, “XML with PHP 5,” talks about the different strategies of parsing XML and converting XML to other formats with XSLT. XML-RPC and SOAP are intro- duced to show you how to implement web services with both techniques. Although not specifically for PHP 5, the five mainstream extensions that Chapter 9,“Mainstream Extensions,” covers are important enough to deserve a place in this book. The first section, “Files and Streams,” explains about han- dling files and network streams. A stream is nothing more than a way to access external data, such as a file, remote URL, or compressed file. The sec- ond section, “Regular Expressions,” explains the syntax of a regular expres- sion engine (PCRE) that PHP uses with numerous examples to show you how these expressions can make your life easier. In “Date Handling,” we explain the different functions used to parse and format date and time strings. In “Graphics Manipulation with GD,” we show you through two real-life scenar- ios the basic functions of creating and manipulating graphics with PHP. The last section in this chapter, “Multibyte Strings and Character Sets,” explains the different character sets and the functions to convert and handle different ones, including multi-byte strings used in Asian languages. Chapter 10, “Using PEAR,” introduces PEAR, the PHP Extension and Application Repository. Starting with concepts and installation, the chapter shows how to use PEAR and maintain the local installed packages. This chap- ter also includes a tour of the PEAR web site. Chapter 11, “Important PEAR Packages,” gives an overview of the most important PEAR packages, along with examples. Packages covered include Template Systems, the Auth package to do authentication, form handling with the HTML_QuickForm package, and a package used to simplify caching. Chapter 12, “Building PEAR Components,” explains how to create your own PEAR package. The PEAR Coding Standard and package.xml package def- inition format, together with tips on including files and package layout, get you on your way to completing your first PEAR package. Chapter 13, “Making the Move,” deals with the few backward-incompatible changes that were introduced between PHP 4 and PHP 5. This chapter tells you which things you need to take care of when making your application work on PHP 5, and provides workarounds wherever possible. Chapter 14, “Performance,” shows you how to make your scripts perform better. The chapter offers tips on standard PHP usage, the use of external util- ities (APD and Xdebug) to find problems in your scripts, and PHP accelerators like APC and Zend Performance Suite.
  • 27. Gutmans_PrefaceFore Page xxvii Thursday, September 23, 2004 9:06 AM A Note About Coding Styles xxvii Chapter 15, “An Introduction to Writing PHP Extensions,” explains how to write your own custom PHP extension. We use a simple example to explain the most important things like parameter parsing and resource management. Chapter 16, “PHP Shell Scripting,” shows you how to write shell scripts in PHP, because PHP is useful for more than just web applications. We care- fully explain the differences between the CLI and CGI executables in which PHP comes, including command-line parameter parsing and process control. This book also includes three appendices. Appendix A, “PEAR and PECL Package Index,” provides an overview of all important packages, with descrip- tions and dependencies on other packages. Appendix B, “phpDocument Format Reference,” explains the syntax as understood by the PHP Documenter tool to generate API documentation from source code. Appendix C, “Zend Studio Quick Start,” is an introduction to working in the Zend Studio IDE. A NOTE ABOUT CODING STYLES There are almost as many coding styles as there are programmers. The PHP examples in this book follow the PEAR coding standard, with the opening curly bracket on the line below the function name. In some cases, we’ve placed the curly bracket on the same line as the function name. We encourage you to adopt the style you are most comfortable with. Note: A code continuation character, ➥, appears at the beginning of code lines that have wrapped down from the line above it. ABOUT THE SOFTWARE Included in the back of this book is a special link to Zend.com, where you can download a fully functional, 90-day trial version of the Zend Studio IDE. Be sure to use the license key printed on the inside back cover of this book when you install Zend Studio. The Zend Development Environment (ZDE) is a convenient tool that integrates an editor, debugger, and project manager to help you develop, man- age, and debug your code. It can connect to your own installed server or directly to the Zend Studio server component. It is a powerful tool that allows you to debug your code in its natural environment. UPDATES AND ERRATA AND DOWNLOADS Updates, errata, and copies of the sample programs used in this book can be found at the following URL: http//php5powerprogramming.com. We encourage you to visit this site.
  • 28. Gutmans_PrefaceFore Page xxviii Thursday, September 23, 2004 9:06 AM xxviii Preface ACKNOWLEDGEMENTS This book could not have been written without feedback from our technical reviewers; therefore, we would like to thank Marcus Börger, Steph Fox, Martin Jansen, and Rob Richards for their excellent comments and feedback. Besides these four reviewers, there are a few more people who helped answer several questions during the writing of this book, more specifically Christian Stocker for helping with the XML chapter, Wez Furlong and Sara Golemon for answering questions about the streams layer, Pierre-Alain Joye for providing some insights in the inner workings of the GD library, and less specifically the PEAR commu- nity for their support and dedication to a great repository of usable PEAR com- ponents. Some sections in this book were contributed by co-authors; Georg Richter contributed the MySQLi section of the database chapter, and Zeev Suraski added the section on Zend's Performance Suite. We would also like to thank Mark L. Taub and the editorial team of Pear- son PTR for the things they are good at doing: organizing, planning, and mar- keting this book, and making sure everything fits together. Thanks to Janet Valade, for helpful developmental editing support, and our project editor Kristy Hart, who helped us wrap up the book under pressure and put the final touches on it. Enjoy! Andi, Stig, and Derick
  • 29. Gutmans_Ch01 Page 1 Thursday, September 23, 2004 2:35 PM C H A P T E R 1 What Is New in PHP 5? “The best way to be ready for the future is to invent it.”— John Sculley 1.1 INTRODUCTION Only time will tell if the PHP 5 release will be as successful as its two prede- cessors (PHP 3 and PHP 4). The new features and changes aim to rid PHP of any weaknesses it may have had and make sure that it stays in the lead as the world’s best web-scripting language. This book details PHP 5 and its new features. However, if you are familiar with PHP 4 and are eager to know what is new in PHP 5, this chapter is for you. When you finish reading this chapter, you will have learned ☞ The new language features ☞ News concerning PHP extensions ☞ Other noteworthy changes to PHP’s latest version 1.2 LANGUAGE FEATURES 1.2.1 New Object-Oriented Model When Zeev Suraski added the object-oriented syntax back in the days of PHP 3, it was added as “syntactic sugar for accessing collections.” The OO model also had support for inheritance and allowed a class (and object) to aggregate both methods and properties, but not much more. When Zeev and Andi Gut- mans rewrote the scripting engine for PHP 4, it was a completely new engine; it ran much faster, was more stable, and boasted more features. However, the OO model first introduced in PHP 3 was barely touched. Although the object model had serious limitations, it was used exten- sively around the world, often in large PHP applications. This impressive use of the OOP paradigm with PHP 4, despite its weaknesses, led to it being the main focus for the PHP 5 release. 1
  • 30. Gutmans_Ch01 Page 2 Thursday, September 23, 2004 2:35 PM 2 What Is New in PHP 5? Chap. 1 So, what were some of the limitations in PHP 3 and 4? The biggest limi- tation (which led to further limitations) was the fact that the copy semantics of objects were the same as for native types. So, how did this actually affect the PHP developer? When assigning a variable (that points to an object) to another variable, a copy of the object would be created. Not only did this impact performance, but it also usually led to obscure behavior and bugs in PHP 4 applications because many developers thought that both variables would point at the same object, which was not the case. The variables were instead pointing at separate copies of the same object. Changing one would not change the other. For example: class Person { var $name; function getName() { return $this->name; } function setName($name) { $this->name = $name; } function Person($name) { $this->setName($name); } } function changeName($person, $name) { $person->setName($name); } $person = new Person("Andi"); changeName($person, "Stig"); print $person->getName(); In PHP 4, this code would print out "Andi". The reason is that we pass the object $person to the changeName() function by-value, and thus, $person is copied and changeName() works on a copy of $person. This behavior is not intuitive, as many developers would expect the Java- like behavior. In Java, variables actually hold a handle (or pointer) to the object, and therefore, when it is copied, only the handle (and not the entire object) is duplicated. There were two kinds of users in PHP 4: the ones who were aware of this problem and the ones who were not. The latter would usually not notice this problem and their code was written in a way where it did not really matter if the problem existed. Surely some of these people had sleepless nights trying to track down weird bugs that they could not pinpoint. The former group dealt with this problem by always passing and assigning objects by reference. This would prevent the engine from copying their objects, but it would be a head- ache because the code included numerous & signs.