<<

VISUAL QUICKPro GUIDE PHP Advanced and Object-Oriented Programming

Larry Ullman

Peachpit Press Visual QuickPro Guide PHP Advanced and Object-Oriented Programming Larry Ullman Peachpit Press 1249 Eighth Street Berkeley, CA 94710 Find us on the Web at: www.peachpit.com To report errors, please send a note to: [email protected] Peachpit Press is a division of Pearson Education. Copyright © 2013 by Larry Ullman Acquisitions Editor: Rebecca Gulick Production Coordinator: Myrna Vladic Copy Editor: Liz Welch Technical Reviewer: Alan Solis Compositor: Danielle Foster Proofreader: Patricia Pane Indexer: Valerie Haynes Perry Cover Design: RHDG / Riezebos Holzbaur Design Group, Peachpit Press Interior Design: Peachpit Press Logo Design: MINE™ www.minesf.com Notice of Rights All rights reserved. No part of this book may be reproduced or transmitted in any form by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior written permission of the publisher. For information on getting permission for reprints and excerpts, contact [email protected].

Notice of Liability The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of the book, neither the author nor Peachpit Press shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the instructions contained in this book or by the computer software and hardware products described in it.

Trademarks Visual QuickPro Guide is a registered trademark of Peachpit Press, a division of Pearson Education. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Peachpit was aware of a trademark claim, the designations appear as requested by the owner of the trademark. All other product names and services identified throughout this book are used in editorial fashion only and for the benefit of such companies with no intention of infringement of the trademark. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. 13-digit ISBN: 978-0-321-83218-4 10-digit ISBN: 0-321-83218-3 9 8 7 6 5 4 3 2 1 Printed and bound in the United States of America Dedication To my good friend Michael K. and his family: I cannot thank you all enough for your continuing friendship, generosity, and kindness over these many years. My utmost thanks to… Jessica, the love of my life, for just about everything. Zoe and Sam, for making my world a better place. Everyone at Peachpit Press for their support, for their dedication to putting out quality books, and for everything else they do to make all this happen. The most excellent editor, Rebecca Gulick, for so many reasons. Liz Welch, for her spot-on copyediting and attention to detail. The production coordinator, Myrna Vladic, the compositor, Danielle Foster, the proofreader, Patricia Pane, and the indexer, Valerie Haynes Perry, who turn my mess of files into an actual book. Alan Solis, for his very, very helpful technical review. Thomas Larsson, for his input on the design patterns chapter. Always helpful to get even one more extra set of eyes! Tjobbe Andrews (h t t p://t a w . o.u k ), for volunteering to create a new HTML5 design for the example chapter. And for doing so on such short notice! Sara, for entertaining the kids so that I can get some work done, even if I’d rather not. The readers, the readers, the readers! Table of Contents

Introduction ...... ix

Chapter 1 Advanced PHP Techniques ...... 1 Multidimensional Arrays ...... 2 Advanced Definitions ...... 17 The Heredoc Syntax ...... 31 Using printf() and sprintf() 37 Review and Pursue ...... 42

Chapter 2 Developing Web Applications 43 Modularizing a Web Site ...... 44 Improved SEO with mod_rewrite ...... 67 Affecting the Browser Cache ...... 75 Review and Pursue ...... 80

Chapter 3 Advanced Database Concepts ...... 81 Storing Sessions in a Database ...... 82 Working with U.S. Zip Codes 96 Creating Stored Functions ...... 108 Displaying Results Horizontally ...... 112 Review and Pursue ...... 118

Chapter 4 Basic Object-Oriented Programming . . . . . 119 OOP Theory ...... 120 Defining a Class ...... 121 Creating an Object ...... 124 The $this Attribute ...... 127 Creating Constructors ...... 133 Creating Destructors ...... 136 Designing Classes with UML 140 Better Documentation with phpDocumentor 143 Review and Pursue ...... 148

Table of Contents v Chapter 5 Advanced OOP ...... 149 Advanced Theories ...... 150 Inheriting Classes ...... 152 Inheriting Constructors and Destructors ...... 157 Overriding Methods 161 Access Control 165 Using the Resolution Operator ...... 172 Creating Static Members ...... 176 Review and Pursue ...... 182

Chapter 6 More Advanced OOP ...... 183 Abstract Classes and Methods ...... 184 Interfaces 191 Traits ...... 197 Type Hinting ...... 203 Namespaces ...... 207 Review and Pursue ...... 212

Chapter 7 Design Patterns ...... 213 Understanding Design Patterns ...... 214 The Singleton Pattern 216 The Factory Pattern 220 The Composite Pattern ...... 225 The Strategy Pattern ...... 233 Review and Pursue ...... 242

Chapter 8 Using Existing Classes ...... 243 Catching Exceptions ...... 244 Extending the Exception Class 251 Using PDO ...... 258 Using the Standard PHP ...... 270 Review and Pursue ...... 282

Chapter 9 Example—CMS with OOP ...... 283 Identifying the Goals ...... 284 Creating the Database ...... 286 Making the Template ...... 290 Writing a Utilities File ...... 294 Creating the Error View File ...... 297

vi Table of Contents Defining the Classes ...... 299 Creating the Home Page ...... 304 Viewing a Page ...... 308 Using HTML_QuickForm2 312 Logging Out ...... 320 Adding Pages ...... 322 Review and Pursue ...... 326

Chapter 10 Networking with PHP ...... 327 Accessing Other Web Sites ...... 328 Working with Sockets 333 Performing IP Geolocation ...... 339 Using cURL ...... 343 Creating Web Services ...... 347 Review and Pursue ...... 352

Chapter 11 PHP and the Server 353 Compressing Files 354 Establishing a cron ...... 363 Using MCrypt ...... 366 Review and Pursue ...... 376

Chapter 12 PHP’s Command-Line Interface 377 Testing Your Installation ...... 378 Executing Bits of Code ...... 383 Interactive PHP CLI ...... 386 Creating a Command-Line Script ...... 388 Running a Command-Line Script ...... 391 Working with Command-Line Arguments . . . . . 395 Taking Input ...... 400 Built-In Server ...... 405 Review and Pursue ...... 408

Chapter 13 XML and PHP 409 What Is XML? 410 XML Syntax 412 Attributes, Empty Elements, and Entities ...... 415 Defining XML Schemas 419 Parsing XML ...... 432

Table of Contents vii Creating an RSS Feed 447 Review and Pursue ...... 452

Chapter 14 Debugging, Testing, and Performance . . . . . 453 Debugging Tools ...... 454 Unit Testing ...... 460 Profiling Scripts ...... 471 Improving Performance 473 Review and Pursue ...... 476

Index ...... 477

viii Table of Contents Introduction

In this humble author’s (or not-so-humble About This Book author’s) opinion, “advanced PHP” is about continuing to learn: you already know how Simply put, I’ve tried to make this book’s to use PHP, and presumably MySQL, for content accessible and useful for every all the standard stuff, and now it’s time to PHP intermediate-level programmer out expand that knowledge. This new knowl- there. As I suggest in the introductory edge can range from how to do different paragraphs, I believe that “advanced” PHP things, how to improve on the things, is mostly a matter of extended topics. You and how other technologies intersect with already possess all the basic knowledge— PHP. In short, you know how to make a you retrieve database query results in your dynamic Web site with PHP, but you’d like sleep—but want to go further. This may to know how to make a better Web site, mean learning object-oriented program- with every possible meaning of “better.” ming (OOP), using PEAR (PHP Extension and Application Repository), invoking PHP This is the approach I’ve taken in writing on the command line, picking up eXtensi- this book. I haven’t set out to blow your ble Markup Language (XML), or fine-tuning mind discussing esoteric idiosyncrasies the aspects of your existing skill set. language has; rewriting the PHP, MySQL, or Apache source code; or making theo- My definition of advanced PHP program- retically interesting but practically useless ming covers three loosely grouped areas: code. In short, I present to you several n Doing what you already do better, hundred pages of beyond-the-norm but faster, and more securely still absolutely necessary (and often cool) n Learning OOP tips and techniques. n Doing standard things using PHP and other technologies (like networking, unit testing, or XML)

Introduction ix This book can be loosely divided into three Unlike with most of my other books, I do sections. The first three chapters cover not expect that you’ll necessarily read this advanced PHP knowledge in general: pro- book in sequential order, for the most part. gramming techniques, Web applications, Some chapters do assume that you’ve and databases. Those chapters all cover read others, like the object-oriented ones, information that the average PHP program- which have a progression to them. Some mer may not be familiar with but should be later chapters also reference examples able to comprehend. In the process, you’ll completed in earlier ones. If you read the pick up lots of useful code, too. later ones first, you’ll just need to skip The next six chapters focus on object- back over to the earlier ones to gener- oriented programming. This section ate whatever database or scripts the later constitutes about half of the book. OOP is chapter requires. explained starting with the fundamentals, Finally, I’ll be using HTML5 in my scripts then going into lots of advanced topics, and instead of HTML. I’ll also use some CSS, as ending with plenty of real-world examples. warranted. I do not discuss either of these The final five chapters are all “PHP and…” subjects in this book (and, to be frank, may chapters: not adhere to them perfectly). If you are not already familiar with the subjects, you n Communicating with networked servers should look at some online resources or n Communicating with the host server good books (such as Elizabeth Castro’s n Using the command-line interface excellent Visual QuickStart Guides) for more information. n XML n Debugging, testing, and performance Most examples used in this book are intended to be applicable in the real world, omitting the frivolous code you might see in other books, tutorials, and manuals. I focus almost equally on the philosophies involved as on the coding itself so that, in the end, you will come away with not just how to do this or that but also how to apply the new skills and ideas to your own projects.

x Introduction What’s new in this edition What You’ll Need I had three goals in writing this new edition: Just as this book assumes that you already n Greatly expanding the coverage possess the fundamental skills to program of OOP in PHP (and, more important, to debug it n Introducing new, more current topics, when things go awry), it also assumes that such as unit testing and debugging you already have everything you need to follow along with the material. For starters, n Cutting content that is outdated or this means a PHP-enabled server. As of this has since been better covered in my writing, the latest version of PHP was 5.4, other books and much of the book depends on your In terms of additional new material, by far using at least PHP 5.3. the biggest change has been the additional Along with PHP, you’ll often need a coverage of object-oriented programming, database application. I use MySQL for the including a chapter on design patterns. examples, but you can use anything. And, There’s also a new example chapter that for the scripts in some of the chapters to uses objects instead of procedural code. work—particularly the last five—your PHP Of course, all of the code and writing has installation will have to include support been refreshed, edited, and improved as for the corresponding technology, and needed. This could mean just switching to that technology’s library may need to be HTML5 and better use of CSS, or my doing installed, too. Fortunately, PHP 5 comes a better job of explaining complex ideas with built-in support for many advanced and examples. features. If the scripts in a particular chap- ter require special extensions, that will be How this book compares referenced in the chapter’s introduction. to my others This includes the few times where I make use of a PEAR or PECL class. Nowhere in Those readers who have come to this book this book will I discuss installation of PHP, from my PHP for the Web: Visual Quick- MySQL, and a Web server, though, as I Start Guide (Peachpit Press, 2011) may find expect you should already know or have themselves in a bit over their heads. This accomplished that. book does assume complete comfort with standard PHP programming, in particular Should you have questions or problems, debugging your own scripts. I’m not sug- you can always search the Web or post a gesting you put this book down, but if you message in my support forums (www.Larry find it goes too fast for you or assumes Ullman.com/forums/) for assistance. knowledge you don’t currently possess, you Beyond PHP, you need the things you may want to check out my PHP and MySQL should already have: a text editor or IDE, for Dynamic Web Sites: Visual QuickPro an FTP application (if using a remote Guide (Peachpit Press, 2011) instead. server), and a Web browser. All of the If you have read the PHP and MySQL code in this book has been tested on both book, or a previous edition of this one, I’m Windows XP and Mac OS X; you’ll see hoping that you’ll find this to be a wonder- screen shots in both operating systems. ful addition to your library and skill set.

Introduction xi Support Web Site I have developed a Web site to support this book, available at www.LarryUllman.com. This site: n Has every script available for download n Has the SQL commands available for download n Has extra files, as necessary, available for download n Lists errors that have been found in the book n Features a support forum where you can get help or assist others n Provides a way to contact me directly I’ll also post at the site articles that extend some of the information covered in this book. When using this site, please make sure you’ve gone to the correct URL (the book’s title and edition are plastered everywhere). Each book I’ve written has its own sup- port area; if you go to the wrong one, the downloadable files won’t match those in the book.

xii Introduction 4 Basic Object-Oriented Programming

Although PHP is still not as strong in its OOP feature set as other languages, In This Chapter object-oriented programming in PHP has a lot going for it. And while it is possible to OOP Theory 120 have a good career without learning and Defining a Class 121 using OOP, you should familiarize yourself Creating an Object 124 with the concept. At the very least, being able to use both OOP and procedural pro- The $this Attribute 127 gramming allows you to better choose the Creating Constructors 133 right approach for each individual project. Creating Destructors 136 In this chapter, and the next (Chapter 5, Designing Classes with UML 140 “Advanced OOP”), I will explain not only the syntax of OOP in PHP 5 and later, but Better Documentation with the key underlying OOP theories as well. In phpDocumentor 143 this chapter, I will use somewhat mundane Review and Pursue 148 examples, but in subsequent chapters, practical, real-world code will be used. Through multiple examples and plenty of explanation, I hope in this book to fully demonstrate not just how you do object- oriented programming in PHP but also when and why. Related to modularity is abstraction: OOP Theory classes should be defined broadly. This is The first thing that you must understand a common and understandable beginner’s about OOP is that it presents not just new mistake. As an example, instead of design- syntax but a new way of thinking about a ing a class for interacting with a MySQL problem. By far the most common mistake database, you should make one that beginning OOP programmers make is to interacts with a nonspecific database. From inappropriately apply OOP theory. PHP will there, using inheritance and overriding, tell you when you make a syntactical mis- you would define a more particular class take, but you’ll need to learn how to avoid for MySQL. This class would look and act theoretical mistakes as well. To explain… like the general database class, but some All programming comes down to taking of its functionality would be customized. actions with data: a user enters data in Another principle of OOP is encapsulation: an HTML form; the PHP code validates it, separating out and hiding how something emails it, and stores it in a database; and so is accomplished. A properly designed class forth. These are simply verbs (actions) and can do everything you need it to do with- nouns (data). With , out your ever knowing how it’s being done. the focus is on the verbs: do this, then this, Coupled with encapsulation is access then this. In OOP, the focus is on the nouns: control or visibility, which dictates how with what types of things will the applica- available components of the class are. tion work? In both approaches, you need Those are the main concepts behind OOP. to identify both the nouns and the verbs You’ll see how they play out in the many required; the difference is in the focus of the OOP examples in this book. But before application’s design. getting into the code, I’ll talk about OOP’s The two most important terms for OOP are dark side. class and object. A class is a generalized First of all, know that OOP is not a better definition of a thing. Think of classes as way to program, just a different way. In blueprints. An object is a specific imple- some cases, it may be better and in some mentation of that thing. Think of objects cases worse. as the house built using the blueprint as a guide. To program using OOP, you design As for the technical negatives of OOP, your classes and then implement them as use of objects can be less efficient than a objects in your programs when needed. procedural approach. The performance dif- ference between using an object or not may One of the tenets of OOP is modularity: be imperceptible in some cases, but you breaking applications into specific subparts. should be aware of this potential side effect. Web sites do many, many things: interact with databases, handle forms, send emails, A second issue that arises is what I have generate HTML, etc. Each of these things already pointed out: misuse and overuse can be a module, which is to say a class. of objects. Whereas bad procedural pro- By separating unrelated (albeit interacting) gramming can be a hurdle to later fix, bad elements, you can develop code indepen- OOP can be a nightmare. However, the dently, make maintenance and updates less information taught over the next several messy, and simplify debugging. chapters should prevent that from being the case for you.

120 Chapter 4 Attributes within classes are a little dif- Defining a Class ferent than variables outside of classes. OOP programming begins with classes, a First, all attributes must be prefixed with a class being an abstract definition of a thing: keyword indicating the variable’s visibility. what information must be stored and what The options are public, private, and functionality must be possible with that protected. Unfortunately, these values information? A User class would be able to won’t mean anything to you until you store information such as the user’s name, understand inheritance (in Chapter 5), ID, email address, and so forth. The func- so until then, just use public: tionality of a User could be login, logout, class ClassName { change password, and more. public $var1, $var2; Syntactically, a class definition begins with function functionName() { the word class, followed by the name of the class. The class name cannot be // Function code. a reserved word and is often written in } uppercase, as a convention. After the class name, the class definition is placed within } curly braces: As shown here, a class’s attributes are class ClassName { listed before any method definitions. } The second distinction between attributes and normal variables is that if an attribute Classes contain variables and functions, is initialized with a set value, that value which are referred to as attributes (or must be a literal value and not the result properties) and methods, respectively of an expression: (you’ll see other terms, too). Collectively, a class’s attributes and methods are called class GoodClass { its members. public $var1 = 123; Functions are easy to add to classes: public $var2 = 'string'; class ClassName { public $var3 = array(1, 2, 3); function functionName() { } // Function code. class BadClass { } // These won't work! } public $today = get_date(); The methods you define within a class public $square = $num * $num; are defined just like functions outside of } a class. They can take arguments, have default values, return values, and so on.

Basic Object-Oriented Programming 121 Note that you don’t have to initialize the attri- Script 4.1 This simple class will allow you to say butes with a value. And, aside from declaring Hello, world! through the magic of objects! (Okay, so it’s completely unnecessary, but it’s a fine variables, all of a class’s other code goes introductory demonstration.) within its methods. You cannot execute state- ments outside of a class method: 1 '; Hello, world! in different languages. 14 15 // Print a message specific to a ➝ language: To define a class: 16 switch ($language) { 1. Create a new PHP document in 17 case 'Dutch': 18 echo 'Hallo, wereld!'; your text editor or IDE, to be named 19 break; HelloWorld.php (Script 4.1): 20 case 'French': '; 40 41 } // End of sayHello() method. 42 43 } // End of HelloWorld class.

122 Chapter 4 3. Begin defining the first (and only) method: break; function sayHello($language = case 'English': ➝ 'English') { default: This class currently contains no attri- echo 'Hello, world!'; butes (variables), as those would have break; been declared before the methods. This method is called sayHello(). It } // End of switch. takes one argument: the language for The switch prints different messages the greeting. based upon the chosen language. For the methods, I normally use the English is the default language, both “lowercase camel” convention: start in the switch and as the value of the with lowercase letters, separating $language argument (see Step 3). Obvi- words with an uppercase letter. This is ously you can easily expand this switch another common convention, although to include more languages, like non- not one as consistently followed as that Western ones. for the class name itself. 6. Complete the sayHello() method: 4. Start the method’s code: e c h o '< /p >'; e c h o '< p >'; } // End of sayHello() method. The method will print Hello, world! in You just need to close the HTML para- one of several languages. The message graph tag. will be wrapped within HTML paragraph 7. Complete the class and the PHP page: tags, begun here. } 5. Add the method’s switch: HelloWorld.php switch ($language) { 8. Save the file as . case 'Dutch': You’ve now created your first class. This isn’t, to be clear, a good use of OOP, echo 'Hallo, wereld!'; but it starts the process and you’ll learn break; better implementations of the concept case 'French': in due time. echo 'Bonjour, monde!'; Note that I’m not using a closing PHP tag, which is my policy for PHP scripts break; to be included by other files. case 'German': echo 'Hallo, Welt!'; Class methods can also have a visibility, break; by preceding the function definition with the appropriate keyword. If not stated, all methods case 'Italian': have an assumed definition of echo 'Ciao, mondo!'; public function functionName() {... break; The class stdClass is already in use case 'Spanish': internally by PHP and cannot be declared in echo '¡Hola, mundo!'; your own code.

Basic Object-Oriented Programming 123 Note that you would not use the property Creating an Object variable’s dollar sign, which is a common Using OOP is a two-step process. The cause of parse errors: first—defining a class—you just did when $object->$propertyName; // Error! you wrote the HelloWorld class. The second step is to make use of that class by (As you’ll also see in the next chapter, the creating an object (or a class instance). ability to reference an object’s method or property in this manner depends upon the Going back to my User class analogy, an member’s visibility.) instance of this class may be for the user with a username of janedoe. The user’s Once you’ve finished with an object, you attributes might be that username, a user can delete it as you would any variable: ID of 2459, and an email address of jane@ unset($object); example.com. This is one instance of the Simple enough! Let’s go ahead and quickly User class. A second instance, john_doe, make use of the HelloWorld class. has that username, a user ID of 439, and an email address of john.doe@example. To create an object: edu. These are separate objects derived from the same class. They are the same in 1. Create a new PHP document in general, but different in specificity. your text editor or IDE, to be named hello_object.php, beginning with the Creating an object is remarkably easy in standard HTML (Script 4.2): PHP once you’ve defined your class. It requires the keyword new: $object = new ClassName(); Now the variable $object exists and is of type ClassName (instead of type string or array). More technically put, $object is an Hello, World! instance of ClassName. this syntax: $object->methodName(); (The -> can be called the object operator.) methodName('value', 32, true); on its own. This PHP page will include To access an object’s properties, use all of the code necessary to make a $object->propertyName; valid HTML page.

124 Chapter 4 Script 4.2 In this page, PHP uses the defined class 2. Include the class definition: in order to say Hello, world! in several different languages. require('HelloWorld.php');

1 In order to create an instance of a class, 2 the PHP script must have access to that 3 class definition A. As the definition is 4 stored in a separate file, that file must be 5 Hello, World! included here. By using require() (as 6 opposed to include()), the script will 7 stop executing with a fatal error if the file 8 could not be included (and there is no 9 sayHello(); 21 $obj->sayHello(); This line of code will call the sayHello() 22 method, which is part of the $obj object. 23 // Say hello in different languages: 24 $obj->sayHello('Italian'); Since the method is not being given any 25 $obj->sayHello('Dutch'); arguments, the greeting will be in the 26 $obj->sayHello('French'); default language of English. 27 28 // Delete the object: 5. Say hello in a few more languages: 29 unset($obj); $obj->sayHello('Italian'); 30 ?> 31 $obj->sayHello('Dutch'); 32 $obj->sayHello('French'); An object’s methods can be called multiple times, like any other function. Different arguments are provided to vary the result. continues on next page

A You’ll see an error like this if you go to create an object whose class definition cannot be found.

Basic Object-Oriented Programming 125 6. Delete the object and complete the page: unset($obj); ?> You don’t technically have to delete the object—it will be deleted as soon as the script ends. Still, I think it’s better B The resulting Web page (the examples will get better, I promise). programming form to tidy up like this. 7. Save the file as hello_object.php and place it in your Web directory, along Analyzing the HelloWorld with HelloWorld.php. Example You don’t have to place both docu- As I state in the first section of this chap- ments in the same directory, but if they ter, OOP is both syntax and theory. For are stored separately, you will need to this first example, the HelloWorld class, change the require() line accordingly. the emphasis is on the syntax. Hopefully you can already see that this isn’t great 8. Test hello_object.php by viewing it in use of OOP. But why? Well, it’s both too your Web browser B. specific and too simple. Having an object Note that you should run hello_ print one string is a very focused idea, object.php, not HelloWorld.php, whereas classes should be much more in your Web browser. abstract. It also makes absolutely no sense to use all this code—and the extra memory required—for one echo state- Class names are not case-sensitive. ment. It’s nice that the object handles However, object names, like any variable in different languages, but still… PHP, are case-sensitive. The HelloWorld class does succeed in Because function names in PHP are not a couple of ways, though. It does dem- case-sensitive, the same is true for method onstrate some of the syntax. And it is names in classes. reusable: if you have a project that needs to say Hello, world! dozens of times, this one object will do it. And if you need to change it to Hello, World! (with a capital “W”), edit just the one file and you’re golden. To that end, however, it’d be better for the method to return the string, rather than just print it, so the string could be used in more ways. Finally, this class kind of reflects the notion of encapsulation: you can use the object to say Hello, world! in multiple languages without any knowledge of how the class does that.

126 Chapter 4 The issue is that within the class itself (i.e., The $this Attribute within a class’s methods), you must use The HelloWorld class actually does some- an alternative syntax to access the class’s thing, which is nice, but it’s a fairly minimal attributes. You cannot do just this: example. The class includes a method, but it class BadClass { does not contain any attributes (variables). public $var; As I say in the section “Defining a Class,” attributes: function do() { // This won't work: n Are variables print $var; n Must be declared as public, private, or protected (I’ll use only public in } this chapter) } n If initialized, must be given a static value The do() method cannot access $var (not the result of an expression) in that manner. The solution is a special Those are the rules for defining a class’s variable called $this. The $this variable attributes, but using those attributes in a class always refers to the current requires one more piece of information. instance (i.e., the object involved) of that As already explained, through the object, class. Within a method, you can refer to you can access attributes via the object the instance of a class and its attributes by notation operator (->): using the $this->attributeName syntax. $object->propertyName; Rather than over-explaining this concept, I’ll go right into another example that puts this new knowledge into action. This next, much more practical, example will define a class representing a rectangle.

Basic Object-Oriented Programming 127 To use the $this variable: Script 4.3 This class is much more practical than the HelloWorld example. It contains two 1. Create a new PHP document in your attributes—for storing the rectangle’s width and text editor or IDE, to be named height—and four methods. Rectangle.php (Script 4.3): 1 width = $w; 18 function setSize($w = 0, $h = 0) { 19 $this->width = $w; $this->height = $h; 20 $this->height = $h; } 21 } 22 The setSize() method takes two argu- 23 // Method to calculate and return ments, corresponding to the width and ➝ the area. height. Both have default values of 0, 24 function getArea() { 25 return ($this->width * just to be safe. ➝ $this->height); Within the method, the class’s attributes 26 } are given values using the numbers 27 28 // Method to calculate and return to be provided when this method is ➝ the perimeter. called (assigned to $w and $h). Using 29 function getPerimeter() { $this->width and $this->height 30 return ( ($this->width + refers to this class’s $width and ➝ $this->height) * 2 ); $height attributes. 31 } 32 33 // Method to determine if the ➝ rectange 34 // is also a square. 35 function isSquare() { 36 if ($this->width == ➝ $this->height) { 37 return true; // Square

script continues on next page

128 Chapter 4 Script 4.3 continued 5. Create a method that calculates and returns the rectangle’s area: 38 } else { 39 return false; // Not a square function getArea() { 40 } 41 } return ($this->width * 42 ➝ $this->height); 43 } // End of Rectangle class. } This method doesn’t need to take any arguments, because it can access the class’s attributes via $this. Calculat- ing the area of a rectangle is simple: multiply the width times the height. This value is then returned. 6. Create a method that calculates and returns the rectangle’s perimeter: function getPerimeter() { return ( ($this->width + ➝ $this->height) * 2 ); } This method is like getArea(), except it uses a different formula. 7. Create a method that indicates if the rectangle is also a square: function isSquare() { if ($this->width == ➝ $this->height) { return true; } else { return false; } } This method compares the rectangle’s dimensions. If they are the same, the Boolean true is returned, indicating the rectangle is a square. Otherwise, false is returned. 8. Complete the class: } // End of Rectangle class. 9. Save the file as Rectangle.php.

Basic Object-Oriented Programming 129 To use the Rectangle class: 5. Print the rectangle’s area: 1. Create a new PHP document in echo '

The area of the rectangle your text editor or IDE, to be named ➝ is ' . $r->getArea() . '

'; rectangle1.php, beginning with the To print the rectangle’s area, you only standard HTML (Script 4.4): need to have the object tell you what that value is by calling its getArea() method. As this method returns the area (instead of printing it), it can be used in an echo statement like this. 6. Print the rectangle’s perimeter: Rectangle echo '

The perimeter ➝ $r->getPerimeter() . '

'; This is a variation on the code in Step 5. 7. Indicate whether or not this rectangle is also a square: This rectangle is '; 2. Include the class definition: if ($r->isSquare()) { require('Rectangle.php'); echo 'also'; 3. Define the necessary variables and print an introduction: } else { $width = 42; echo 'not'; $height = 7; } echo "

With a width of $width echo ' a square.

'; ➝ and a height of $height...

"; Since the isSquare() method returns 4. Create the object and assign the rect- a Boolean value, I can invoke it as a angle’s dimensions: condition. This code will print either This rectangle is also a square. or This $r = new Rectangle(); rectangle is not a square. $r->setSize($width, $height); 8. Delete the object and complete the page: The first line creates an object of type u n s e t($r); Rectangle. The second line assigns the values of the variables in this ?> script—$width and $height—to the object’s attributes. The values here are assigned to $w and $h in the setSize() method when it’s called, which are 9. Save the file as rectangle1.php and then assigned to $this->width and place it in your Web directory, along $this->height within that method. with Rectangle.php. continues on page 132

130 Chapter 4 Script 4.4 The Rectangle class is used in this PHP script. The rectangle’s dimensions are first assigned to the class’s attributes by invoking the setSize() method, and then various properties of the rectangle are reported.

1 2 3 4 5 Rectangle 6 7 8 9 With a width of $width and a height of $height..."; 23 24 // Create a new object: 25 $r = new Rectangle(); 26 27 // Assign the rectangle dimensions: 28 $r->setSize($width, $height); 29 30 // Print the area: 31 echo '

The area of the rectangle is ' . $r->getArea() . '

'; 32 33 // Print the perimeter: 34 echo '

The perimeter of the rectangle is ' . $r->getPerimeter() . '

'; 35 36 // Is this a square? 37 echo '

This rectangle is '; 38 if ($r->isSquare()) { 39 echo 'also'; 40 } else { 41 echo 'not'; 42 } 43 echo ' a square.

'; 44 45 // Delete the object: 46 unset($r); 47 48 ?> 49 50

Basic Object-Oriented Programming 131 10. Test rectangle1.php by viewing it in your Web browser A. 11. Change the variables’ values in rectangle1.php and rerun it in your Web browser B.

Having get_and set methods in a class is a common convention. Methods starting with set are used to assign values to class attributes. Methods starting with get are used A Various attributes for a rectangle are revealed to return values: either attributes or the results using the Rectangle class. of calculations.

Methods can call each other, just as they would any other function, but you’ll need to use $this again. The following is unnecessary but valid: function getArea() { if ($this->isSquare()) { return ($this->width * $this->width); B If the width and height are the same, the } else { rectangle is also a square. return ($this->width * $this->height); } }

Analyzing the Rectangle Example The Rectangle class as defined isn’t perfect, but it’s pretty good, if I do say so myself. It encap- sulates all the things you might want to do with or know about a rectangle. The methods also only handle calculations and return values; no HTML is used within the class, which is a better way to design. One criticism may be that the class is too specific. Logically, if you’ve created a site that performs a lot of geometry, the Rectangle class might be an inherited class from a broader Shape. You’ll learn about inheritance in the next chapter. From the first two examples you can see the benefit of objects: the ability to create your own data type. Whereas a string is a variable type whose only power is to contain characters, the Rectangle is a new, powerful type with all sorts of features.

132 Chapter 4 Because the constructor is still just another Creating Constructors method, it can take arguments, and values A constructor is a special kind of method that for those arguments can be provided when differs from standard ones in three ways: the object is created: n Its name is always _ _construct(). class User { n It is automatically and immediately function _ _construct($id) { called whenever an object of that class // Function code. is created. } n It cannot have a return statement. } The syntax for defining a constructor is therefore $me = new User(2354); Rectangle class ClassName { The class could benefit from hav- ing a constructor that assigns the rectangle’s public $var; dimensions when the rectangle is created. function _ _construct() { // Function code. To add and use a constructor: } 1. Open Rectangle.php (Script 4.3) in your text editor or IDE. } 2. After declaring the attributes and before A constructor could be used to connect to defining the setSize() method, add the a database, set cookies, or establish initial constructor (Script 4.5): values. Basically, you’ll use constructors to do whatever should always be done—and done function _ _construct($w = 0, first—when an object of this class is made. ➝ $h = 0) { $this->width = $w; $this->height = $h; } continues on next page

Script 4.5 A constructor has been added to the Rectangle class. This makes it possible to assign the rectangle’s dimensions when the object is created.

1

script continues on next page

Basic Object-Oriented Programming 133 This method is exactly like the setSize() Script 4.5 continued method, albeit with a different name. 11 Note that constructors are normally the 12 class Rectangle { first method defined in a class (but still 13 defined after the attributes). 14 // Declare the attributes: 15 public $width = 0; 3. Save the file as Rectangle.php. 16 public $height = 0; 4. Open rectangle1.php (Script 4.4) in 17 your text editor or IDE. 18 // Constructor: 19 function _ _construct($w = 0, 5. If you want, change the values of ➝ $h = 0) { the $width and $height variables 20 $this->width = $w; (Script 4.6): 21 $this->height = $h; 22 } $width = 160; 23 24 // Method to set the dimensions: $height = 75; 25 function setSize($w = 0, $h = 0) { 6. Change the way the object is created 26 $this->width = $w; so that it reads 27 $this->height = $h; 28 } $r = new Rectangle($width, 29 ➝ $height); 30 // Method to calculate and return ➝ the area: The object can now be created and the 31 function getArea() { rectangle assigned its dimensions in 32 return ($this->width * one step. ➝ $this->height); 33 } 7. Delete the invocation of the setSize() 34 method. 35 // Method to calculate and return ➝ the perimeter: This method is still part of the class, 36 function getPerimeter() { though, which makes sense. By 37 return ( ($this->width + keeping it in there, you ensure that a ➝ $this->height) * 2 ); rectangle object’s size can be changed 38 } after the object is created. 39 40 // Method to determine if the ➝ rectange 41 // is also a square. 42 function isSquare() { 43 if ($this->width == $this->height) { 44 return true; // Square 45 } else { 46 return false; // Not a square 47 } 48 49 } 50 51 } // End of Rectangle class.

134 Chapter 4 Script 4.6 This new version of the script assigns 8. Save the file as rectangle2.php, place the rectangle’s dimensions when the object is it in your Web directory along with the created (thanks to the constructor). new Rectangle.php (Script 4.5), and 1 test in your Web browser A. 2 3 4 A constructor like the one just added 5 Rectangle to the Rectangle class is called a default 6 its arguments. This means that a Rectangle 7 8 object can be created using either of these 9 _ _construct(); 18 // Define the necessary variables: 19 $width = 160; With the Rectangle example, this would let 20 $height = 75; you get rid of the setSize() method without 21 losing the ability to resize a rectangle. 22 // Print a little introduction: 23 echo "

With a width of $width and a In PHP 4 and in other programming ➝ height of $height...

"; languages (like C++), a constructor is declared 24 by creating a method whose name is the same 25 // Create a new object: 26 $r = new Rectangle($width, $height); as the class itself. 27 28 // Print the area. If PHP 5 cannot find a _ _construct() 29 echo '

The area of the rectangle method in a class, it will then try to find a con- ➝ is ' . $r->getArea() . '

'; structor whose name is the same as the class 30 (the PHP 4 constructor naming scheme). 31 // Print the perimeter. 32 echo '

The perimeter of the rectangle ➝ is ' . $r->getPerimeter() . '

'; 33 34 // Is this a square? 35 echo '

This rectangle is '; 36 if ($r->isSquare()) { 37 echo 'also'; 38 } else { 39 echo 'not'; 40 } 41 echo ' a square.

'; 42 43 // Delete the object: A The resulting output is not affected by 44 unset($r); the incorporation of a constructor in the 45 Rectangle class. 46 ?> 47 48

Basic Object-Oriented Programming 135 Creating Destructors Autoloading Classes The corollary to the constructor is the When you define a class in one script destructor. Whereas a constructor is that is referenced in another script, you automatically invoked when an object is have to make sure that the second script created, the destructor is called when the includes the first, or there will be errors. object is destroyed. This may occur when To that end, PHP 5 supports a special you overtly remove the object: function called _ _autoload (note that functions in PHP beginning with two $obj = new ClassName(); are special ones). unset($obj); // Calls destructor, too. The _ _autoload() function is invoked Or this may occur when a script ends (at when code attempts to instantiate an which point PHP releases the memory object of a class that hasn’t yet been used by variables). defined. The _ _autoload() function’s goal is to include the corresponding file. Being the smart reader that you are, you In simplest form, this might be have probably already assumed that the function _ _autoload ($class) { destructor is created like so: require($class . '.php'); class ClassName { } // Attributes and methods. For each new object type created in function _ _destruct() { the following code, the function will be // Function code. invoked: } $obj = new Class(); } $me = new Human(); Destructors do differ from constructors and $r = new Rectangle(); other methods in that they cannot take any Thanks to the _ _autoload() function, arguments. those three lines will automatically The Rectangle class used in the last two include Class.php, Human.php and examples doesn’t lend itself to a logical Rectangle.php (within the current directory). destructor (there’s nothing you need to do when you’re done with a rectangle). And Notice that this _ _autoload() function rather than do a potentially confusing but is defined outside of any class; instead, practical example, I’ll run through a dummy it is placed in a script that instantiates the objects. example that shows how and when con- structors and destructors are called. The previous edition of this book dem- onstrated use of the _ _autoload() function, but that approach has been deprecated in favor of using the Standard PHP Library (SPL). It will be discussed in Chapter 8, “Using Existing Classes.”

136 Chapter 4 To create a destructor: 3. Create the constructor: 1. Create a new PHP document in your function _ _construct() { text editor or IDE, to be named demo. echo '

In the constructor.

'; php, beginning with the standard HTML (Script 4.7): } The constructor doesn’t do anything but print a message indicating that it has been invoked. This will allow you to trace when the class’s automatic meth- ods are called. Create the destructor: Constructors and 4. ➝ Destructors function _ _destruct() { In the destructor.

'; ➝ href="style.css"> } 5. Complete the class: }

Script 4.7 This script doesn’t do anything except best convey when constructors and destructors are called.

1 2 3 4 5 Constructors and Destructors 6 7 8 9

script continues on next page

Basic Object-Oriented Programming 137 6. Define a simple function that also Script 4.7 continued creates an object: 16 // Define the class: function test() { 17 class Demo { 18 echo '

In the function. 19 // No attributes. ➝ Creating a new object...

'; 20 21 // Constructor: $f = new Demo(); 22 function _ _construct() { echo '

About to leave the 23 echo '

In the constructor.

'; ➝ f u n c t i o n .< /p >'; 24 } 25 } 26 // Destructor: To best illuminate the life of objects, 27 function _ _destruct() { 28 echo '

In the destructor.

'; which affects when constructors and 29 } destructors are called, I’m adding this 30 simple function. It prints messages and 31 } // End of Demo class. creates its own object, which will be a 32 variable that’s local to this function. 33 // Define a test() function: 34 function test() { 7. Create an object of class Demo: 35 echo '

In the function. Creating a ➝ ne w object...

'; echo '

Creating a new object... 36 $f = new Demo(); ➝ < /p >'; 37 echo '

About to leave the ➝ function.

'; $o = new Demo(); 38 } When this object is created, the con- 39 structor will be called. So this script first 40 // Create the object: prints this line (Creating a new object…) 41 echo '

Creating a new object...

'; 42 $o = new Demo(); and will then print In the constructor. 43 8. Call the test() function: 44 // Call the test() function: 45 echo '

Calling the function...

'; echo '

Calling the function... 46 test(); ➝ < /p >'; 47 48 // Delete the object: te st(); 49 echo '

About to delete the object... After printing the status statement, the ➝

'; function is called. Consequently, the 50 unset($o); 51 function is entered, wherein In the func- 52 echo '

End of the script.

'; tion. Creating a new object... will first 53 ?> be printed. Then, in that function, a new 54 object is created (called $f). Therefore, 55 the constructor will be called again, and the In the constructor. message printed, as you’ll see in the final output.

138 Chapter 4 After the object is created in the func- tion, the About to leave the function. message is printed. Then the function is exited, at which point in time the object defined in the function—$f—goes away, A The flow of thus invoking the $f object’s destructor, the two objects’ creation and printing In the destructor. destruction over 9. Delete the $o object: the execution of the script is echo '

About to delete the revealed by this ➝ o b j e c t...

'; script. In particular, you can see unset($o); how the test() function’s object, Once this object is deleted, its destruc- $f, lives and dies tor is invoked. in the middle of this script. 10. Complete the page: echo '

End of the script.

'; ?> 11. Save the file as demo.php and place it in B If you don’t forcibly delete the your Web directory. Then test by view- object A, it will ing it in your Web browser A. be deleted when the script stops 12. Delete the unset($o) line, save the file, running. This and rerun it in your Web browser B. means that the $o object’s destructor Also check the HTML source code is called after of this page C to really understand the final printed the flow. message, even after the closing (Arguably, you could also delete the HTML tags . C About to delete the object… line, although I did not for the two figures.)

In C++ and C#, the destructor’s name for the class ClassName is ~ClassName, the cor- ollary of the constructor, which is ClassName. Java does not support destructors.

C The $o object’s destructor is called as the very last script event, when the script stops running. Thus, the In the destructor. message gets sent to the browser after the closing HTML tag.

Basic Object-Oriented Programming 139 Designing Classes with UML A How UML represents To this point, the chapter has discussed a class graphically. OOP in terms of both syntax and theory, but there are two other related topics worth exploring, both new additions to this edition. Benefits of a Class Design First up is an introduction to Unified Model- ing Language (UML), a way to graphically While making a formal UML class design may at first appear to be more of an exer- represent your OOP designs. Entire books cise than anything, there are concrete are written on the subject, but since this benefits to creating one. First of all, if chapter covers the fundamentals of OOP, I’ll you sketch out the design before doing also introduce the fundamentals of UML. any coding, you improve your chances of A class at its core has three components: getting the code correct from the start. In other words, if you put the effort into n Its name your visual design, and ponder whether n Its attributes the design fully reflects the application’s needs, you minimize the number of times n Its methods you’ll need to update your class defini- UML graphically represents a class by cre- tions down the road. ating a class diagram: a three-part box for Second, a principle of OOP is encapsu- each class, with the class name at the top. lation: separating out and hiding how The next section of the box would identify something is accomplished. A UML, with the class attributes, and the third would list its listing of attributes, methods, and the methods A. arguments, can act as a user guide for those classes. Any code that requires For the attributes, the attribute type (e.g., classes that have been modeled should string, array, etc.) is listed after the attri- be able to use the classes, and its meth- bute’s name, as in ods and attributes, without ever looking userId:number at the underlying code. In fact, you can distribute the UML along with your code username:string as a service to your clients. If the attribute had a default value, you could reflect that too: width:number = 0 To define a method in a class diagram, you would start with the method name, placing its arguments and types within parenthe- ses. This is normally followed by the type of value the method returns: sayHello(language:string):void The sayHello() method doesn’t return anything, so its return type is void.

140 Chapter 4 With this in mind, you can complete the class diagram for the HelloWorld class B. In the next steps, you’ll design the diagram B A UML representation of the simple HelloWorld class. that reflects the Rectangle class.

To design a class using UML: 1. Using paper or software, draw a three- part box. If you like the feeling of designing with paper and pencil, feel free, but there are also plenty of software tools that can fulfill this role, too. Search online for an application that will run on your platform, or for a site that can serve the same purposes within the browser. 2. Add the name of the class to the top of the box: Rectangle Use the class’s proper name (i.e., the same capitalization). 3. Add the attributes to the middle section: width:number = 0 height:number = 0 Here are the two attributes for the Rectangle class. Both are numbers with default values of 0. 4. Add the constructor definition to the third part of the box: _ _construct(width:number = ➝ 0, height:number = 0):void This method is named _ _ c o n s t r u c t. It takes two arguments, both of type num- ber, and both with default values of 0. The method does not return anything, so its return value is void. continues on next page

Basic Object-Oriented Programming 141 5. Add the setSize() method definition: setSize(width:number = ➝ 0, height:number = 0):void The setSize() method happens to be defined exactly like _ _construct(). 6. Add the getArea() method definition: ge t A rea():n u m b er C A UML representation of the simple Rectangle class. The getArea() method takes no argu- ments and returns a number. 7. Add the getPerimeter() method definition: getPerimeter():number The getPerimeter() method also takes no arguments and returns a number. 8. Add the isSquare() method definition: isSquare():Boolean This method takes no arguments but returns a Boolean value. 9. Save your design for later reference C.

Be certain to update your class design should you later change your class definition.

In the next chapter, in which more com- plex OOP theory is unveiled, you’ll learn more UML techniques.

142 Chapter 4 Although you can adequately document Better Documentation your code using simple comments, as I do with phpDocumentor in this book, there are two obvious ben- efits to adopting a formal phpDocumentor Along with creating a UML class design, approach: another new topic in this edition is n It conveys many best practices and creating better code documentation recommended styles. using phpDocumentor (www.phpdoc.org). n phpDocumentor will generate docu- In my opinion, properly documenting one’s mentation, in HTML and other formats, code is so vitally important that I wish PHP for you. would generate errors when it came across a lack of comments! Having taught PHP The generated HTML A can also be a and interacted with readers for years, I am valuable resource for anyone using your amazed at how often programmers omit code, particularly your classes. comments, occasionally under the guise of waiting until later. Proper documentation is something that should be incorporated into code for your own good, for your client’s, for your co-workers’ (if applicable), and for the programmer in the future who may have to alter or augment your work—even if that programmer is you.

A The generated HTML documentation for the HelloWorld class.

Basic Object-Oriented Programming 143 phpDocumentor creates documentation by After the description, write one or more reading the PHP code and your comments. lines of tags. Each tag is prefaced by @, To facilitate that process, you would start and phpDocumentor supports several writing your comments in a way that php- kinds; which you use will depend on the Documentor understands. To begin, you’ll thing you’re documenting. use the docblock syntax: A docblock can be placed before any of /** the following: * n Class definition * Short description n Function or method definition * n Variable declaration * Long description n Constant definition * Tags n File inclusion */ A docblock should be written at the top of The short description should be a single a script, in order to document the entire file line description. The long description can (Script 4.8). go over multiple lines and even use some HTML. Both are optional.

Script 4.8 A more formally documented version of the HelloWorld class.

1 8 * @copyright 2012 9 */ 10 11 /** 12 * The HelloWorld class says "Hello, world!" in different languages. 13 * 14 * The HelloWorld class is mostly for 15 * demonstration purposes. 16 * It's not really a good use of OOP. 17 */ 18 class HelloWorld { 19 20 /** 21 * Function that says "Hello, world!" in different languages. 22 * @param string $language Default is "English" 23 * @returns void 24 */

script continues on next page

144 Chapter 4 Script 4.8 continued To document a variable declaration, you use the @var tag, followed by the variable’s 25 function sayHello($language = ➝ 'English') { type (and optional description): 26 /** 27 // Put the greeting within P tags: 28 echo '

'; * @var string 29 */ 30 // Print a message specific to a ➝ language: $name = 'Larry Ullman'; 31 switch ($language) { 32 case 'Dutch': Notice that the docblock doesn’t need 33 echo 'Hallo, wereld!'; to reference the variable name, as php- 34 break; Documentor will be able to read that from 35 case 'French': the following line of code. The point of 36 echo 'Bonjour, monde!'; the docblock is to indicate the variable’s 37 break; 38 case 'German': intended type. 39 echo 'Hallo, Welt!'; To document methods and functions, use 40 break; @param to detail the function’s parameters 41 case 'Italian': 42 echo 'Ciao, mondo!'; and @return to indicate the type of value 43 break; the function returns (Script 4.8). 44 case 'Spanish': The details as to the possible types, and 45 echo '¡Hola, mundo!'; 46 break; the full usage of all of phpDocumentor, 47 case 'English': can be found in the documentation 48 default: (www.phpdoc.org/docs/). 49 echo 'Hello, world!'; 50 break; Once you’ve written comments in the 51 } // End of switch. proper format, you can use the phpDocu- 52 mentor tool to generate your documen- 53 // Close the HTML paragraph: tation. To do that, you must first install 54 echo '

'; phpDocumentor. The best way to install it 55 56 } // End of sayHello() method. is using PEAR (http://pear.php.net), so 57 you must have that installed, too. PEAR 58 } // End of HelloWorld class. already comes installed with many all-in- one WAMP, MAMP, or LAMP stacks; check your associated documentation if you’re using one of these. If not, see the sidebar for some tips on installing PEAR.

Basic Object-Oriented Programming 145 To use phpDocumentor: 3. Add the phpDocumentor PEAR channel : 1. Complete the phpDocumentor-type B comments for a file (Script 4.8) or pear channel-discover application. ➝ pear.phpdoc.org For simplicity’s sake, Script 4.8 shows a This will allow you to download the fully documented HelloWorld.php. latest version of the phpDocumentor directory from that site. 2. Access your computer via the com- mand-line interface. 4. Install phpDocumentor C: My assumption is that you already know pear install phpdoc/ how to do this for your platform. If not, phpDocumentor-alpha search the Web or use my support This instruction comes straight from forums for answers. the phpDocumentor Web site. It may change in time; check the site for the best, current instructions.

B Adding the phpDocumentor channel to my PEAR installation.

C Installing phpDocumentor in PEAR.

146 Chapter 4 Note that on my system, in both Step Installing PEAR Packages 3 and Step 4, I had to preface these One PEAR-related thing I do not discuss commands with sudo, to invoke the in this book is the installation process, for superuser, and include the full path to two good reasons. First, with the varia- PEAR (both suggestions are made in tions of available operating systems, it’s the sidebar). too tough to nail down comprehensive 5. Move to the directory where your PHP instructions for all potential readers. scripts are: Second, experience tells me that many users are on hosted servers, where they cd /path/to/folder cannot directly install anything. 6. Document a single file using Still, installing PEAR is not impossibly phpdoc -f HelloWorld.php -t docs hard, and once you master the installa- tion of a single package, installing more That line tells phpDocumentor to parse is a snap. If you want to try your hand at the file HelloWorld.php and to write installing PEAR packages, start by check- the output to the target (-t) directory ing out the PEAR manual, which has docs, which would be a folder in that instructions. If you’re still not clear as to same directory. phpDocumentor will what you should do, search the Web for attempt to create that directory, if it articles on the subject, particular to your does not exist. operating system, and/or post a question in the book’s supporting forum, where I’ll 7. Open docs/index.html in your be happy to assist. browser A. Some installation tips up front: .. You may need to invoke the For the sake of saving precious book pear installer as a superuser (or space, the code in this book will not be docu- using sudo). mented using the full phpDocumentor syntax. .. Make sure that the location of To view documentation mistakes, check your PEAR directory is in your PHP out the generated errors. include path. To have phpDocumentor document an .. Run the command pear help entire project, you can have it parse the cur- install to see what options rent directory using are available. phpdoc -d . -t docs If you are on a hosted server, the host- ing company should be willing to install If you want, you can edit the templates PEAR packages for you (which benefit used by phpDocumentor to output HTML more every user on the server). If they won’t to your liking. do that, you ought to consider a differ- ent hosting company (seriously). Barring that, you can install PHP and PEAR on your own computer in order to use phpDocumentor.

Basic Object-Oriented Programming 147 Pursue Review and Pursue n Come up with another (relatively simple) If you have any problems with these sec- class. Define and use it in PHP. Then tions, either in answering the questions or model and document it using UML and pursuing your own endeavors, turn to the phpDocumentor. book’s supporting forum (www.Larry n Learn more about UML, if you are so Ullman.com/forums/). inclined. n Find UML software that you like (for Review your platform or online). n How does OOP differ from procedural n Learn more about phpDocumentor, if programming? (See page 120.) you are so inclined. n What is a class? What is an object? n Add phpDocumentor-style comments to What is an attribute (or property)? What the Rectangle class and then generate is a method? (See page 121.) its documentation. n What syntax do you use to create a class? To create an object? (See pages 121 and 124.) n How do you create class methods? How do you call object methods? (See pages 121 and 124.) n How do you create class attributes? How do you reference those attributes within the class? How do you reference those attributes using an object? (See pages 121, 124, and 127.) n What is a constructor? How do you cre- ate one? When is a constructor called? (See page 133.) n What is a destructor? How do you cre- ate one? When is a destructor called? (See page 136.) n What is UML? How do you represent a class in UML? (See page 140.) n What is phpDocumentor? What are the arguments for using it? (See page 143.) n What is a docblock? (See page 144.)

148 Chapter 4 Index

Symbols add_page.html script, beginning, 324 add_page.php script <<<, using with heredoc syntax, 31 beginning, 322 & (ampersand), using with variables, 30 submit button, 324 % (percent sign), using in strings, 41 add_task.php script :: (scope resolution operator), using, 172–175, 177 beginning, 10, 260 ; (semicolon), use with stored functions, 109 for prepared statements, 266 " (quotation marks), using with classes, 152 for SELECT query, 264 for sprintf(), 39 A Advanced PHP Debugger, downloading, 454 abstract classes ampersand (&), using with variables, 30 versus classes, 184 Andrews, Tjobbe, 290 creating, 186 anonymous functions declaring attributes, 188 calling, 27 defining constructors, 188 downside, 27 Heron’s Formula, 188 using, 27–29 versus interfaces, 191, 196 antipatterns, explained, 232 Triangle class, 186–189 Apache Abstract Factory pattern versus Factory, 224 configuration, 67 abstract methods enabling URL rewriting, 71 creating, 186 making improvements with, 285 declaring attributes, 188 array() function, replacing calls to, 2. See also multidimensional arrays; short array defining constructors, 188 syntax Heron’s Formula, 188 assertions, using with unit tests, 462 access control attributes establishing for methods, 165 in classes, 121 importance of, 166 protecting, 171 indicating in UML, 166 rules for definition of, 127 in OOP, 151 versus static variables, 177 private level, 165–166 autocompletion, support for, 387 protected level, 165 _ _autoload() function, invoking, 136 public level, 165 autoload.php file, saving, 279 restriction of, 165 accessor, explained, 171

Index 477 B defining in OOP, 121–123 b type specifier, meaning of, 37 deriving from parents, 153–156 backing up database, 356–357 designing with UML, 140–142 backtrace, printing, 50 functions in, 121 behavioral patterns get and set methods, 132 explained, 215 inheriting, 152–156 using, 233 inheriting from, 153–156 books1.xml document, beginning, 413 instanceof keyword, 152 books1.xml file, opening, 416 loosely coupled, 209 bootstrap file methods, 121 confirming module file, 60 in OOP, 120 creating, 57–60 relationship between, 203 header file, 60 , 123 main page, 57–60 using quotation (“) marks with, 152 purpose, 57 variables in, 121 switch conditional, 59–60 ClassName, destructor’s name for, 139 validating, 59 ClassName::methodName() syntax, explained, 175 browser cache, affecting, 75–79 CLI (command-line interface). See also C interactive PHP CLI backticks, 403 c type specifier, meaning of, 37 built-in Web server, 405–407 cache header types, 75 versus CGI (Common Gateway cache-control directives, 75 Interface), 378 Cache-Control header type, 75, 79 code blocks, 384–385 caching. See also server caches command-line arguments, 395–399 affecting, 76–79 creating command-line script, 388–390 pages, 75 creating interface, 399 CGI (Common Gateway Interface), versus CLI exec() backtick, 403 (command-line interface), 378 executing bits of code, 383–385 check_urls.php document, creating, 334 fscanf() function for input, 400 class attributes, accessing, 127–132 -h option, 378 class constants versus static attributes, 176 -i option, 378 class design, benefits, 140 -m option, 378 class versus object names, case-sensitivity, 126 pcntl (process control) extension, 403 classes. See also inheritance; OOP (object- php.ini, 388 oriented programming) remote server, 384 versus abstract classes, 184 running command-line script, 391–394 attributes in, 121 system() backtick, 403 autoloading, 136 taking user input, 400–404 components, 140 testing installation, 378 creating objects from, 156 using, 378 defining for CMS with OOP example, -v option, 378 299–303 verifying version of, 381

478 Index CLI installation testing Color Blue HTML5 design, using, 52 on Mac OS X, 381–382 command-line arguments on Unix, 381–382 alternative usage, 399 on Windows 7, 379–380 number.php script, 395 client URLs (cURL) utility. See cURL (client using, 396–399 URLs) utility command-line script _ _ c l o n e ( ) method, defining, 197 checking syntax without running, 394 CMS (content management system), 283 creating, 388–390 CMS with OOP example. See also OOP running in Mac OS X, 394 (object-oriented programming) running in Unix, 394 categories table, 286 running in windows, 391–393 comments table, 286 Co m pany.p h p script, beginning, 208 creating pages, 289 Composite design, creating, 226–230 creating users, 289 Composite pattern creatorId, 288 considering, 225 database, 286–289 described, 225 defining classes, 299–303 example of, 232 error view file, 297–298 implementing, 225 footer for template, 291–293 subclasses, 226 header file for template, 290 using with , 232 header for template, 291–293 composite.php script, beginning, 231 home page, 304–307 composition home page view, 306–307 “has a” relationship, 203 HTML_QuickForm2, 312–319 indicating in UML, 203 MVC (Model-View-Controller) approach, using, 209 284–285 compressing files, 354–362 Page class, 299–301 config.inc.php script, beginning, 45 pages, 284 Config.php script, beginning for Singleton pages table, 286, 288 class, 217 pages versus posts, 286 configuration file, for modularized site, 45–51 site organization, 285 constants, assigning values to, 176 tags table, 286 _ _construct() method, looking for, 135 template, 290–293 constructors. See also destructors three-include approach for template, 290 calling directly, 135 User class, 301–303 creating in OOP, 133–135 user type structure, 289 declaring, 135 users, 284 default, 135 users table, 286–287, 289 inheriting, 157–160 utilities file, 294–296 for static members, 178–179 viewing pages, 308–311 subclass, 158–160 code documentation, importance of, 143 syntax, 133 code library, organizing, 208 using, 133–135 collection.dtd document, creating, 422 content management system (CMS). See CMS collection.xsd document, creating, 428 with OOP example

Index 479 content modules, creating, 61–63 sorting tasks, 16 creational patterns submission conditional, 14 explained, 215 using, 9 using, 225 databases. See also zip codes cron service backing up, 356–357 adding items to files, 363 distance calculations, 102–107 asterisk (*) parameter, 363 optimizing joins, 103 crontab format, 363 session functions, 84 establishing, 363–365 session handlers, 85–91 establishing for PHP file, 364–365 session table, 82–83 setting ranges with hyphen (-), 363 SHOW WARNINGS command, 99 crontab file, using, 365 storage of session data, 82, 85–87 CRUD functionality, using iCrud interface for, stores table, 100–101 192–193 zip codes, 96–99 cURL (client URLs) utility db_backup.php document, creating, 355 beginning transaction, 345 db_sessions script, beginning, 85 executing transaction, 345 DBG debugging tool, downloading, 454 invoking, 343 debugging tools POST data, 345 Advanced PHP Debugger, 454 POST method, 345 DBG, 454 redirects, 345 Xdebug, 454 timeout, 345 DECLARE statement, using with variables, 108 using, 343–346 decrypting data with MCrypt, 372–375 cURL library, 344 delimiter, changing for stored functions, 109–110 curl_errno() function, 346 demo document, creating, 137 curl_getinfo() function, 346 design patterns curl.php script antipatterns, 232 creating, 343 behavioral, 215, 233 running, 351 components, 214 Composite, 225–232 D creational, 215, 225 d type specifier, meaning of, 37 Factory, 220–224 data Gang of Four, 215 decrypting with MCrypt, 372–375 Iterator, 273–277 encrypting with MCrypt, 367–371 Singleton, 216–219 database file, creating for modularized site, 45 Strategy, 233–241 database-driven arrays structural, 215, 225 adding tasks, 10–16 destructors. See also constructors connecting to database, 10 creating, 136–139 displaying tasks, 16 inheriting, 157–160 HTML form, 13 for static members, 179 retrieving tasks, 14 directories securing task value, 14 protecting, 70 selecting columns, 8 restricting access, 70

480 Index displaying results horizontally, 112–117 file functions display.p h p script, beginning, 112 fgetc(), 404 distance calculations, performing, 102–107 fgetcsv(), 404 docblocks, using, 144–145 using on STDIN, 404 documentation files, compressing, 354–362 importance of, 143 final definition, using with functions, 163 viewing mistakes, 147 footer.html file, saving, 56 documenting footer.inc.php file, saving, 293 functions, 145 fopen() methods, 145 versus fsocketopen(), 338 variable declarations, 145 using, 328, 333 DTD, associating with XML file, 419–420 fscanf() function, using, 41, 400 fsocketopen() E versus fopen(), 338 e type specifier, meaning of, 37 using, 333–338 encapsulation FTP port number, 333 explained, 166 function definitions use in OOP, 120, 126, 140 anonymous functions, 27–29 encrypting data with MCrypt, 367–371 recursive, 17–24 error handling, purpose of, 460 static variables, 24–26 error view file, creating, 297–298 function parameters er ror.html document, beginning, 297 making copies of variables, 30 Exception class, extending, 251–257 passing by reference, 30 exception handling, purpose of, 460 passing by value, 30 exceptions, catching, 244–250, 259–260 type hinting, 15 Expat functions. See also stored functions functions resource, 439 documenting, 145 parsing XML with, 433 final definition, 163 expat.php document, creating, 434 and references, 30 Expires cache header type, 75, 79 G F Gang of Four, 215 f type specifier, meaning of, 37 garbage collection, using with session Factory pattern handlers, 90 versus Abstract Factory, 224 geolocation information, fetching, 340 consequence, 224 get and set methods, using with classes, 132 creating, 220–224 get_quote.php document, creating, 329 described, 220 getter, explained, 171 using, 220 variation, 224 H factor y.p h p script “has a” relationship, explained, 203 for autoloading classes, 279 header() function, using in caching, 75–77 beginning, 222 header.html file, saving, 55 fetch() method, using, 262 header.inc.php script, using, 291

Index 481 hello_object.php document, creating, processing form data, 315–318 124–126 registerRule(), 315 HelloWorld example validating forms, 314, 322–323 analyzing, 126 validation rules, 314 class documentation, 143–144 HTTP status codes, 334 HelloWorld.php document, creating, 122 httpd.conf file, opening, 68 heredoc syntax comparing to nowdoc, 36 I encapsulating strings, 31–36 iCrud interface, declaring, 192–193 EOD delimiter, 32 IMAP port number, 333 EOT delimiter, 32 index page using, 31–36 confirming module file, 60 Heron’s Formula, using with triangles, 188 creating, 57–60 hinting.php script header file, 60 beginning, 204 main page, 57–60 for Iterator interface, 274 purpose, 57 home page switch conditional, 59–60 creating for CMS with OOP example, validating, 59 304–307 index.html script, beginning, 306 t r y...c a tc h block, 304 index.php script view, 306–307 beginning, 57 horizontal results, displaying, 112–117 for home page, 304 .htaccess overrides inheritance. See also classes; objects; OOP allowing, 67–69 (object-oriented programming) AllowOverride , 68 attributes, 150 Directory directive, 68 base class, 150 protecting directories, 70, 285 child class, 150–151 HTML tags versus XML tags, 410 derived class, 150 HTML template design, 160 creating, 52–56 indicating in UML, 150 creating pages, 52–56 “is a” relationships, 203 footer file, 56 members of classes, 150 header file, 53–54 methods, 150 HTML_QuickForm2 parent class, 150–151 add a page View file, 324–325 process of, 152 adding pages, 322–325 super class, 150 creating forms, 313, 322–323 terminology, 150 element types, 313 using, 120, 209 filtering form data, 314 inheriting HTML element types, 313 classes, 152–156 logging out, 320–321 constructors, 157–160 login form, 312 destructors, 157–160 login View file, 318–319 instanceof keyword, using with classes, 152 login.php script, 315–318

482 Index interactive PHP CLI. See also CLI (command- J line interface) joins, optimizing, 103 support for autocompletion, 387 JSON format, using with Web services, 348 using, 386–387 interface keyword, using, 191 L interface.php script, beginning, 192 lambdas interfaces calling, 27 versus abstract classes, 191, 196 downside, 27 associating classes with, 191 using, 27–29 benefit of, 196 Last-Modified cache header type, 75, 78 creating, 191 LDAP port number, 333 defining constructors, 194 load testing, explained, 476 indicating in UML, 196 local variables. See also variables meanings of, 196 creating for stored function, 110 versus traits, 200 declaring, 108 using, 192–196 login.html script, beginning, 318 IP addresses, unreliability of, 342 login.php script IP geolocation creating, 315–318 accuracy, 342 email address, 317 finding user’s location, 339–342 form submission, 317 gethostbyaddr() function, 342 password field, 317 gethostbyname() function, 342 validating form data, 317 MaxMind option, 341 logout.php script, beginning, 320 options, 341 performing, 339–342 M ip_geo.php script, creating, 339 main.inc.php script, beginning, 61 “is a” relationship, explained, 203 max-age cache-control directive, iSort interface, implementing, 235–236 meaning of, 75 iSort Strategy pattern, 239–240 MaxMind IP geolocation, features of, 341 iSort.php script, beginning, 235 MCrypt Iterator design pattern decrypting data, 372–375 examples in SPL, 273 encrypting data, 367–371 using, 273–277 using with PHP, 366 Iterator interface member access, controlling, 166–171. See also current() method, 274 static members DirectoryIterator, 277 methods FilterIterator, 277 accessors, 171 implementing, 275–276 constructors, 133–135 key() method, 274, 277 defining in OOP, 121 LimitIterator, 277 documenting, 145 next() method, 274, 277 establishing visibility of, 165 rewind() method, 274, 277 getters, 171 using, 274–277 mutators, 171 valid() method, 274, 277 overriding, 161–164, 173–174

Index 483 mod_rewrite module, 285 MySQL database allowing .htaccess overrides, 67–69 accessing, 83 enabling URL rewriting, 71–74 calculating distances, 103–107 implementing, 72 using, 67–74 N Model-View-Controller (MVC), using with CMS namespace class, using, 210–211 and OOP, 284–285 namespace keyword, placement of, 211 modularity, use in OOP, 120 _ _NAMESPACE_ _ constant, 211 modularizing Web sites. See also Web sites namespace.php script, beginning, 210 comments, 48 namespaces configuration file, 45–51 defining, 207 content modules, 61–63 features of, 207 creating database file, 45 limitations, 207 debugging level, 49 referencing, 208, 211 email address for errors, 48 subnamespaces, 207 error handling, 49–50 using, 208–210 explained, 44 using in multiple files, 211 HTML template, 52–56 networking index page, 51, 57–60 accessing Web sites, 328–332 printing error and backtrace, 50 classes in PEAR, 332 running script, 48 cURL, 343–346 search module, 64–66 IP geolocation, 339–342 server-side constants, 49 sockets, 333–338 site structure, 50 Web services, 347–351 multidimensional arrays. See also array() Zend Framework classes, 332 function no-cache directive, meaning of, 75 adding tasks to databases, 10–16 nowdoc syntax, comparing to heredoc, 36 database-driven, 8–10 number format, specifying printing of, 38 defining, 6 number2 script, creating, 396 grade sorting function, 7 number.php script, creating, 389 name-sorting function, 6 printing as defined, 7 O short array syntax, 2 o type specifier, meaning of, 37 sorting, 4–8, 29 object versus class names, case-sensitivity, 126 for Strategy design, 240 object-oriented programming (OOP). See OOP two-dimensional, 3–4 (object-oriented programming) usort() function, 4 objects. See also inheritance must-revalidate cache-control directive, cloning, 197 meaning of, 75 copying, 197 mutator, explained, 171 creating from classes, 156 MVC (Model-View-Controller), using with CMS creating in OOP, 124–126 and OOP, 284–285 serializing, 294 mysql client, SHOW WARNINGS command, 99 use in OOP, 120

484 Index OOP (object-oriented programming). See also P classes; CMS with OOP example Page class $this attribute, 127–132 creating for CMS with OOP example, abstract classes, 184–190 299–301 access control, 120, 165–171 getter methods, 300 accessing class attributes, 127–132 page.html script, beginning, 311 attributes versus variables, 121 Page.php script, beginning, 299 autoloading classes, 136 page.php script, beginning, 308 calling object methods, 125 page-viewing page classes, 120 catching exceptions, 310 composition, 203, 209 Controller, 309 constructors, 133–135 creating, 308–310 controlling member access, 166–171 throwing exceptions, 310 creating objects, 124–126 validating page ID, 310 defining classes, 121–123 page-viewing View, creating, 311 design approaches, 209 parse_url() function destructors, 136–139 using with sockets, 333–334, 336 encapsulation, 120, 126, 140, 166 validating URLs, 338 inheritance, 120, 150, 209 parsing XML. See also XML (Extensible Markup installing PEAR packages, 147 Language) interfaces, 191–196 changing case-folding, 439 methods, 184–190 event-based parser, 432 modularity, 120 with Expat, 433 modularizing application files, 278 with PHP, 434–439 namespaces, 207–211 SimpleXML, 440–446 objects, 120 tree-based parser, 432 overriding, 120 patterns overriding methods, 161–164 antipatterns, 232 phpDocumentor, 143–147 behavioral, 215, 233 polymorphism, 151 components, 214 recommendation, 160 Composite, 225–232 scope resolution operator (::), 172–175 creational, 215, 225 static members, 176–181 Factory, 220–224 taking actions with data, 120 Gang of Four, 215 theory, 120 Iterator, 273–277 traits, 197–202 Singleton, 216–219 type hinting, 203–206 Strategy, 233–241 visibility, 120, 123, 151 structural, 215, 225 opcode caching, implementing, 473 pcntl (process control) extension, using with overriden methods, referring to, 173–174 CLI, 403 overriding PDO (PHP Data Objects) methods, 161–164 calling quote() method, 262 use in OOP, 120 catching exceptions, 259 changing error reporting, 261

Index 485 PDO (continued) setting up tests, 467–470 connecting to database, 258–259 setUp() method for testing, 467–468, 470 described, 258 Simpletest alternative, 460 executing queries, 261–262 testing Rectangle class, 469 prepared statements, 266–269 $this object, 464 preventing SQL injection attacks, 262 upgrading PEAR, 461 running SELECT queries, 264 phpunit command, executing, 465 SELECT queries, 262–263 polymorphism, use in OOP, 151 using, 260–261 POP port number, 333 PDO object, creating, 260 port numbers for sockets, 333 PEAR (PHP Extension and Application Pragma cache header type, 75 Repository) prepared statements installing phpDocumentor in, 146 performance benefits, 269 networking classes, 332 try block, 266 upgrading for unit testing, 461 using through PDO, 266–269 PEAR packages, installing, 147 printf() function percent (%) sign, using in strings, 41 formats, 37 performance, improving, 473–475 type specifiers, 37 Pet example inheritance design, 160 using, 37–38 pets1.php script printing beginning, 153 backtrace, 50 for overriding methods, 162 numbers and strings, 38 pets2.php script, for scope resolution operator private cache-control directive, meaning of, 75 (::), 172 profile log, viewing in webgrind, 474–475 PHP, parsing XML with, 434–439 profiling scripts, 471–472 PHP and server proxy server, explained, 75 compressing files, 354–362 proxy-revalidate cache-control directive, establishing cron, 363–365 meaning of, 75 MCrypt, 366–375 public cache-control directive, meaning of, 75 PHP CLI. See CLI (command-line interface) public variables, accessing, 169. See also PHP Data Objects (PDO). See PDO (PHP Data variables Objects) PHP output, compressing, 362 Q phpDocumentor queries, executing, 261–262 docblocks, 144–145 query caching, availability of, 473 features, 143–144 query() method, using, 262 installing, 145 query results, displaying horizontally, 112–117 using, 146–147 QuickForm2 PHPUnit. See also unit testing add a page View file, 324–325 creating test cases, 463–465 adding pages, 322–325 defining tests, 462–463 creating forms, 313, 322–323 downloading, 460 element types, 313 installing, 461–462 filtering form data, 314 invoking assertion methods, 464 HTML element types, 313 running tests, 465–466

486 Index logging out, 320–321 scripts, profiling, 471–472 login form, 312 search module login View file, 318–319 creating, 64–66 login.php script, 315–318 printing caption, 66 processing form data, 315–318 printing results, 66 registerRule(), 315 search.inc.php script, beginning, 64 validating forms, 314, 322–323 SELECT queries validation rules, 314 executing, 262–263 quotation (") marks, using with classes, 152 populating menu in form, 265 running, 264 R setFetchMode() method, 262 read_mcrypt.php script, beginning, 372 setting fetch mode, 264 Rectangle class try block, 264 constructor added to, 133–135 semicolon (;), use with stored functions, 109 using, 130–132, 201–202 SEO, improving with mod_rewrite, 67–74 Rectangle example, analyzing, 132 serializing objects, 294 Rectangle.php script server for constructors, 133–135 compressing files, 354–362 creating, 128 establishing cron, 363–365 for tDebug trait, 200 MCrypt, 366–375 recursive functions. See also static variables server caches, implementing, 473. adding debugging line, 23 See also caching adding tasks to array, 22 server commands, running, 374 calling, 21–22 service.php script, creating, 349 defining, 18 session data foreach loop and function, 22 function for destruction of, 89 looping through array, 21 storing as serialized array, 89 nested list of tasks, 19–20 storing in databases, 82, 85–87 using, 17–23 session directory, changing for security, 82 references and functions, 30 session functions, defining, 84 remote server, using with PHP CLI, 384 session handlers results, displaying horizontally, 112–117 creating, 85–91 RSS feed garbage collection function, 90 Atom offshoot format, 451 using, 91–95 channel content, 447 SessionHandlerInterface class, 270 creating, 447–451 sessions table, creating, 82–83 generating, 448–449 sessions.php script, beginning, 91 rss.php script, beginning, 448 set and get methods, using with classes, 132 set_mcrypt.php script, beginning, 369 S ShapeFactory class, using, 222–224 s type specifier, meaning of, 37 ShapeFactory.php script, beginning for Factory pattern, 220 scanf() function, using, 41 Shape.php script, beginning, 186 scope resolution operator (::), using, 172–175, 177 short array syntax, using, 2. See also array() function

Index 487 SHOW WARNINGS command, running, 99 exceptions, 273 Simpletest unit testing Web site, 460 file handling, 271 SimpleXML iterators, 273–277 asXML() method, 446 SplFixedArray, 278 using, 440–446 temporary files, 272 simplexml.php document, creating, 441 using, 270 Singleton class, creating, 217–218 SPL interfaces Singleton pattern ArrayAccess, 279 Config class, 217–219 Countable, 279 described, 216 SplFileObject, using, 272 implementing, 216 SplTempFileObject, described, 272 UML representation, 216 sprintf() function sites. See also modularizing Web sites formats, 37 accessing, 328–332 type specifiers, 37 reading with PHP, 329–332 using, 39–41 s-maxage cache-control directive, using with session data, 88 meaning of, 75 SQP injection attacks, preventing, 261–262 SMTP port number, 333 square.php script, creating, 158 sockets SSH port number, 333 connections, 334–335 SSL port number, 333 explained, 333 Standard PHP Library (SPL). See SPL (Standard fsocketopen(), 333–338 PHP Library) FTP port, 333 static attributes GET request, 336 versus class constants, 176 HEAD request, 336 using with static methods, 178–180 HTTP status codes, 334 static members, creating, 178–181. See also IMAP port, 333 member access LDAP port, 333 static variables. See also recursive functions; parse_url() function, 333–334, 336 variables POP port, 333 versus attributes, 177 ports, 333 using, 24–26 SMTP port, 333 static.php script, beginning, 178 SSH port, 333 stock quotes, retrieving, 329–332 SSL port, 333 stored functions. See also functions Telnet port, 333 ; (semicolon) in code blocks, 109 Web ports, 333 arguments section, 109 sort.php script changing delimiters, 109–110 for anonymous functions, 28 code section, 109 beginning, 4 creating, 109–111 for static variables, 24 declaring, 108–112 SPL (Standard PHP Library) local variable, 110 autoloading capability, 281 stores table autoloading classes, 278–280 address selection, 101 data structures, 278 creating, 100–101 populating, 101

488 Index Strategy design versus interfaces, 200 class definition, 239 precedence, 202 constructor, 237 support for, 197 creating, 235–238 using, 198–199 display() method, 240 triangle iSort classes, 238–241 calculating area of, 188 iSort interface, 235 setting sides of, 190 multidimensional arrays, 240 Triangle class sort() method, 237–239 creating, 186–189 Strategy pattern as extension of Shape, 187 described, 233 using, 189–190 example of, 234 Triangle.php script, beginning, 186 using, 233–234 try block strate g y.p h p script, beginning, 238 using with prepared statements, 266 strings. See also _ _toString() method using with SELECT queries, 264 encapsulating, 31–36 type hinting percent signs, 41 for arrays, 206 printing, 38 function parameters, 15 structural patterns for functions, 206 explained, 215 for interfaces, 206 using, 225 performing, 203 subclass constructors, creating, 158–160 triggering exceptions, 206 switch statement using, 204–206 using with classes, 123 using in functions, 206 using with index page, 59 type specifiers, 37

T U tags, HTML versus XML, 410 u type specifier, meaning of, 37 TDD (test-driven development), 461 UML (Unified Modeling Language) tDebug trait, using, 200 for classes, 140–142 Telnet port number, 333 for composition, 203 temperature script, beginning, 400 for inheritance, 150 $this attribute for interfaces, 196 use in OOP, 127–132 for visibility, 166 using with PHPUnit, 464 UML representation, of Singleton pattern, 216 to-do list, nesting, 9 unit testing. See also PHPUnit _ _toString() method, defining in classes, assertions, 462 184. See also strings benefits, 460 trait keyword, using, 197 implementing, 460 trait.php script, beginning, 201 TDD (test-driven development), 461 traits Xdebug debugging tool, 465 creating, 197 URL rewriting, enabling, 71–74 incorporating into classes, 202

Index 489 User class W attributes of, 152 warnings, showing, 99 creating for CMS with OOP example, Web port numbers, 333 301–303 Web services user input creating, 347–351 prompting for, 402 JSON format, 348 taking in CLI, 400–404 REST (Representational State Transfer), 347 user-defined functions returning types of data, 348 anonymous functions, 27–29 stateless, 347 recursive functions, 17–23 technologies related to, 410 static variables, 24–26 using, 342 User.php script, beginning, 301 Web sites. See also modularizing Web sites usort() function, using, 4 accessing, 328–332 utilities file reading with PHP, 329–332 catching PDO exceptions, 296 webgrind database connection, 296 downloading, 471 serialize() function, 294 installing, 471 serializing objects, 294 loading in browser, 474 starting session, 295 using Xdebug with, 471–472 writing, 294–296 viewing profile log in, 474–475 utilities.inc.php script, beginning, 295 w rite_to_file.p hp script, opening, 272

V X variable declaration, documenting, 145 x type specifier, meaning of, 37 variables, passing by reference, 30. See also Xdebug debugging tool public variables; static variables checking code coverage, 465 view_tasks.php script customizing, 458 beginning, 18 downloading, 454 for caching, 76 ini_set() function, 458 header() function, 76–77 installation requirements, 454 for heredoc syntax, 32 installing on Windows, 455–456 modifying, 33–34 on *nix systems, 454 visibility profiling in, 471 establishing for methods, 165 using, 457–459 importance of, 166 using with webgrind, 471–472 indicating in UML, 166 XML (Extensible Markup Language). See also in OOP, 151 parsing XML private level, 165–166 adding books to file, 414 protected level, 165 & entity, 415 public level, 165 ' entity, 415 restriction of, 165 attributes, 415–418 visibility script, beginning, 166 benefit, 424 Visitor pattern, using with Composite, 232 elements, 415–418 vprintf() function, using, 41 entities, 415–418

490 Index > entity, 415 XSD document < entity, 415 complex types, 427 modifying, 441 creating attributes, 427 overview, 410–411 defining elements, 426 " entity, 415 incorporating, 425 RSS feed, 447–451 mixed attribute on elements, 431 using formal PHP tags with, 439 simple types, 427 valid, 419 using, 425 well formed, 419 xmlns attribute, 425 writing, 413–414 XML document, 413 Z XML Schemas Zend Framework, network-related classes, 332 defining, 419–431 zip codes. See also databases defining attributes, 421–422 database, 96–99 defining elements, 420–421 importing data, 98 prolog, 412 r+ mode, 355 rules for elements, 412 verifying support for, 354 white space, 413 w mode, 355 XML tags versus HTML tags, 410 w+ mode, 355 XML version, indicating, 412 x mode, 355 ZIP archives, 362

Index 491