| short texts for web-programmers |
| 1 | PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential background on the PHP language. It describes the nature and history of PHP, which platforms it runs on, and how to configure it. This chapter ends by showing you PHP in action, with a quick walkthrough of several PHP programs that illustrate common tasks, such as processing form data, interacting with a database, and creating graphics. |
| 2 | What Does PHP Do? PHP can be used in three primary ways: Server-side scripting PHP was originally designed to create dynamic web content, and it is still best suited for that task. To generate HTML, you need the PHP parser and a web server through which to send the coded documents. PHP has also become popular for generating XML documents, graphics, Flash animations, PDF files, and so much more. |
| 3 | Command-line scripting PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might use the command-line scripts for system administration tasks, such as backup and log parsing; even some CRON job type scripts can be done this way (nonvisual PHP tasks). |
| 4 | Client-side GUI applications Using PHP-GTK, you can write full-blown, cross-platform GUI applications in PHP. In this book, however, we concentrate on the first item: using PHP to develop dynamic web content. www.it-ebooks.info |
| 5 | PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, Ubuntu, Debian, and Solaris to Windows and Mac OS X. It can be used with all leading web servers, including Apache, Microsoft IIS, and the Netscape/iPlanet servers. The language itself is extremely flexible. For example, you aren’t limited to outputting just HTML or other text files—any document format can be generated. PHP has built- in support for generating PDF files, GIF, JPEG, and PNG images, and Flash movies. |
| 6 | One of PHP’s most significant features is its wide-ranging support for databases. PHP supports all major databases (including MySQL, PostgreSQL, Oracle, Sybase, MS-SQL, DB2, and ODBC-compliant databases), and even many obscure ones. Even the more recent NoSQL-style databases like SQLite and MongoDB are also supported. With PHP, creating web pages with dynamic content from a database is remarkably simple. |
| 7 | Finally, PHP provides a library of PHP code to perform common tasks, such as database abstraction, error handling, and so on, with the PHP Extension and Application Repos- itory (PEAR). PEAR is a framework and distribution system for reusable PHP compo- nents. You can find out more about it here. A Brief History of PHP Rasmus Lerdorf first conceived of PHP in 1994, but the PHP that people use today is quite different from the initial version. To understand how PHP got where it is today, it is useful to know the historical evolution of the language. Here’s that story, with ample comments and emails from Rasmus himself. |
| 8 | Announcing the Personal Home Page Tools (PHP Tools) version 1.0. These tools are a set of small tight cgi binaries written in C. They perform a number of functions including: . Logging accesses to your pages in your own private log files . Real-time viewing of log information . Providing a nice interface to this log information . Displaying last access information right on your pages . Full daily and total access counters . Banning access to users based on their domain 2 | Chapter 1: Introduction to PHP |
| 9 | . Password protecting pages based on users' domains . Tracking accesses ** based on users' e-mail addresses ** . Tracking referring URL's - HTTP_REFERER support . Performing server-side includes without needing server support for it . Ability to not log accesses from certain domains (ie. your own) . Easily create and display forms . Ability to use form information in following documents Here is what you don't need to use these tools: . You do not need root access - install in your ~/public_html dir . You do not need server-side includes enabled in your server . You do not need access to Perl or Tcl or any other script interpreter . You do not need access to the httpd log files |
| 10 | The only requirement for these tools to work is that you have the ability to execute your own cgi programs. Ask your system administrator if you are not sure what this means. The tools also allow you to implement a guestbook or any other form that needs to write information and display it to users later in about 2 minutes. The tools are in the public domain distributed under the GNU Public License. Yes, that means they are fr For a complete demonstration of these tools, point your browser at: http://www.io.org/~rasmus |
| 11 | Rasmus Lerdorf rasmus@io.org http://www.io.org/~rasmus Note that the URL and email address shown in this message are long gone. The language of this announcement reflects the concerns that people had at the time, such as pass- word-protecting pages, easily creating forms, and accessing form data on subsequent pages. The announcement also illustrates PHP’s initial positioning as a framework for a number of useful tools. |
| 12 | The announcement talks only about the tools that came with PHP, but behind the scenes the goal was to create a framework to make it easy to extend PHP and add more tools. The business logic for these add-ons was written in C—a simple parser picked tags out of the HTML and called the various C functions. It was never in the plan to create a scripting language. |
| 13 | So what happened? Rasmus started working on a rather large project for the University of Toronto that needed a tool to pull together data from various places and present a nice web-based administration interface. Of course, he used PHP for the task, but for performance reasons, the various small tools of PHP 1 had to be brought together better and inte- grated into the web server. |
| 14 | Initially, some hacks to the NCSA web server were made, to patch it to support the core PHP functionality. The problem with this approach was that as a user, you had to replace your web server software with this special, hacked-up version. Fortunately, Apache was starting to gain momentum around this time, and the Apache API made it easier to add functionality like PHP to the server. |
| 15 | Over the next year or so, a lot was done and the focus changed quite a bit. Here’s the PHP 2.0 (PHP/FI) announcement that was sent out in April 1996: From: rasmus@madhaus.utcs.utoronto.ca (Rasmus Lerdorf) Subject: ANNOUNCE: PHP/FI Server-side HTML-Embedded Scripting Language Date: 1996/04/16 Newsgroups: comp.infosystems.www.authoring.cgi PHP/FI is a server-side HTML embedded scripting language. It has built-in access logging and access restriction features and also support for embedded SQL queries to mSQL and/or Postgres95 backend databases. |
| 16 | It is most likely the fastest and simplest tool available for creating database-enabled web sites. It will work with any UNIX-based web server on every UNIX flavour out there. The package is completely free of charge for all uses including commercial. |
| 17 | Feature List: . Access Logging Log every hit to your pages in either a dbm or an mSQL database. Having hit information in a database format makes later analysis easier. . Access Restriction Password protect your pages, or restrict access based on the refering URL plus many other options. . mSQL Support Embed mSQL queries right in your HTML source files . Postgres95 Support Embed Postgres95 queries right in your HTML source files . DBM Support DB, DBM, NDBM and GDBM are all supported . RFC-1867 File Upload Support Create file upload forms . Variables, Arrays, Associative Arrays . User-Defined Functions with static variables + recursion . Conditionals and While loops |
| 18 | This was the first time the term “scripting language” was used. PHP 1’s simplistic tag- replacement code was replaced with a parser that could handle a more sophisticated embedded tag language. By today’s standards, the tag language wasn’t particularly sophisticated, but compared to PHP 1 it certainly was. |
| 19 | The main reason for this change was that few people who used PHP 1 were actually interested in using the C-based framework for creating add-ons. Most users were much more interested in being able to embed logic directly in their web pages for creating conditional HTML, custom tags, and other such features. PHP 1 users were constantly requesting the ability to add the hit-tracking footer or send different HTML blocks conditionally. This led to the creation of an if tag. Once you have if, you need else as well, and from there it’s a slippery slope to the point where, whether you want to or not, you end up writing an entire scripting language. |
| 20 | By mid-1997, PHP version 2 had grown quite a bit and had attracted a lot of users, but there were still some stability problems with the underlying parsing engine. The project was also still mostly a one-man effort, with a few contributions here and there. At this point, Zeev Suraski and Andi Gutmans in Tel Aviv, Israel, volunteered to rewrite the underlying parsing engine, and we agreed to make their rewrite the base for PHP version 3. Other people also volunteered to work on other parts of PHP, and the project changed from a one-person effort with a few contributors to a true open source project with many developers around the world. |
| 21 | Here is the PHP 3.0 announcement from June 1998: June 6, 1998 -- The PHP Development Team announced the release of PHP 3.0, the latest release of the server-side scripting solution already in use on over 70,000 World Wide Web sites. This all-new version of the popular scripting language includes support for all major operating systems (Windows 95/NT, most versions of Unix, and Macintosh) and web servers (including Apache, Netscape servers, WebSite Pro, and Microsoft Internet Information Server). |
| 22 | PHP 3.0 also supports a wide range of databases, including Oracle, Sybase, Solid, MySQ, mSQL, and PostgreSQL, as well as ODBC data sources. New features include persistent database connections, support for the SNMP and IMAP protocols, and a revamped C API for extending the language with new features. "PHP is a very programmer-friendly scripting language suitable for people with little or no programming experience as well as the seasoned web developer who needs to get things done quickly. The best thing about PHP is that you get results quickly," said |
| 23 | "Version 3 provides a much more powerful, reliable, and efficient implementation of the language, while maintaining the ease of use and rapid development that were the key to PHP's success in the past," added Andi Gutmans, one of the implementors of the new language core. "At Circle Net we have found PHP to be the most robust platform for rapid web-based application development available today," said Troy Cobb, Chief Technology Officer at Circle Net, Inc. "Our use of PHP has cut our development time in half, and more than doubled our client satisfaction. PHP has enabled us to provide database-driven dynamic solutions which perform at phenomenal speeds." |
| 24 | PHP 3.0 is available for free download in source form and binaries for several platforms at http://www.php.net/. The PHP Development Team is an international group of programmers who lead the open development of PHP and related projects. For more information, the PHP Development Team can be contacted at core@php.net. |
| 25 | The Widespread Use of PHP Figure 1-1 shows the usage of PHP as collected by W3Techs as of May 2012. The most interesting portion of data here is the almost 78% of usage on all the surveyed websites. If you look at the methodology used in their surveys, you will see that they select the top 1 million sites (based on traffic) in the world. As is evident, PHP has a very broad adoption indeed! |
| 26 | Installing PHP As was mentioned above, PHP is available for many operating systems and platforms. Therefore, you are encouraged to go to this URL to find the environment that most closely fits the one you will be using and follow the appropriate instructions. |
| 27 | From time to time, you may also want to change the way PHP is configured. To do that you will have to change the PHP configuration file and restart your Apache server. Each time you make a change to PHP’s environment, you will have to restart the Apache server in order for those changes to take effect |
| 28 | PHP’s configuration settings are maintained in a file called php.ini. The settings in this file control the behavior of PHP features, s uch as session handling and form processing. Later chapters refer to some of the php.ini options, but in general the code in this book does not require a customized configuration. See http://php.net/manual/configuration .file.php for more information on php.ini configuration. |
| 29 | PHP pages are generally HTML pages with PHP commands embedded in them. This is in contrast to many other dynamic web page solutions, which are scripts that generate HTML. The web server processes the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1 shows a complete PHP page. |
| 30 | Language Basics This chapter provides a whirlwind tour of the core PHP language, covering such basic topics as data types, variables, operators, and flow control statements. PHP is strongly influenced by other programming languages, such as Perl and C, so if you’ve had ex- perience with those languages, PHP should be easy to pick up. If PHP is one of your first programming languages, don’t panic. We start with the basic units of a PHP pro- gram and build up your knowledge from there. |
| 31 | Lexical Structure The lexical structure of a programming language is the set of basic rules that governs how you write programs in that language. It is the lowest-level syntax of the language and specifies such things as what variable names look like, what characters are used for comments, and how program statements are separated from each other. |
| 32 | Case Sensitivity The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo, while, class, etc., are case-insensitive. Thus, these three lines are equivalent: echo("hello, world"); ECHO("hello, world"); EcHo("hello, world"); Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different variables. Statements and Semicolons A statement is a collection of PHP code that does something. It can be as simple as a variable assignment or as complicated as a loop with multiple exit points. Here is a |
| 33 | small sample of PHP statements, including function calls, assignment, and an if statement: echo "Hello, world"; myFunction(42, "O'Reilly"); $a = 1; $name = "Elphaba"; $b = $a / 25.0; if ($a == $b) { echo "Rhyme? And Reason?"; } PHP uses semicolons to separate simple statements. A compound statement that uses curly braces to mark a block of code, such as a conditional test or loop, does not need a semicolon after a closing brace. Unlike in other languages, in PHP the semicolon before the closing brace is not optional: if ($needed) { echo "We must have it!"; // semicolon required here } // no semicolon required here after the brace The semicolon, however, is optional before a closing PHP tag: <?php if ($a == $b) { echo "Rhyme? And Reason?"; } echo "Hello, world" ?> // no semicolon required before closing tag It’s good programming practice to include optional semicolons, as they make it easier to add code later. |
| 34 | Whitespace and Line Breaks In general, whitespace doesn’t matter in a PHP program. You can spread a statement across any number of lines, or lump a bunch of statements together on a single line. For example, this statement: raisePrices($inventory, $inflation, $costOfLiving, $greed); could just as well be written with more whitespace: raisePrices ( ); $inventory , $inflation , $costOfLiving , $greed or with less whitespace: raisePrices($inventory,$inflation,$costOfLiving,$greed); |
| 35 | You can take advantage of this flexible formatting to make your code more readable (by lining up assignments, indenting, etc.). Some lazy programmers take advantage of this freeform formatting and create completely unreadable code—this is not recommended. |
| 36 | Comments Comments give information to people who read your code, but they are ignored by PHP at execution time. Even if you think you’re the only person who will ever read your code, it’s a good idea to include comments in your code—in retrospect, code you wrote months ago could easily look as though a stranger wrote it. |
| 37 | A good practice is to make your comments sparse enough not to get in the way of the code itself but plentiful enough that you can use the comments to tell what’s happening. Don’t comment obvious things, lest you bury the comments that describe tricky things. For example, this is worthless: $x = 17; // store 17 into the variable $x whereas the comments on this complex regular expression will help whoever maintains your code: // convert &#nnn; entities into characters $text = preg_replace('/&#([0-9])+;/e', "chr('\\1')", $text); |
| 38 | PHP provides several ways to include comments within your code, all of which are borrowed from existing languages such as C, C++, and the Unix shell. In general, use C-style comments to comment out code, and C++-style comments to comment on code. |
| 39 | Shell-style comments When PHP encounters a hash mark character (#) within the code, everything from the hash mark to the end of the line or the end of the section of PHP code (whichever comes first) is considered a comment. This method of commenting is found in Unix shell scripting languages and is useful for annotating single lines of code or making short notes. |
| 40 | Because the hash mark is visible on the page, shell-style comments are sometimes used to mark off blocks of code: Sometimes they’re used before a line of code to identify what that code does, in which case they’re usually indented to the same level as the code: if ($doubleCheck) { # create an HTML form requesting that the user confirm the action echo confirmationForm(); } |
| 41 | Short comments on a single line of code are often put on the same line as the code: $value = $p * exp($r * $t); # calculate compounded interest When you’re tightly mixing HTML and PHP code, it can be useful to have the closing PHP tag terminate the comment: <?php $d = 4; # Set $d to 4. ?> Then another <?php echo $d; ?> Then another 4 C++ comments |
| 42 | When PHP encounters two slashes (//) within the code, everything from the slashes to the end of the line or the end of the section of code, whichever comes first, is considered a comment. This method of commenting is derived from C++. The result is the same as the shell comment style. Here are the shell-style comment examples, rewritten to use C++ comments: |
| 43 | if ($doubleCheck) { // create an HTML form requesting that the user confirm the action echo confirmationForm(); } $value = $p * exp($r * $t); // calculate compounded interest <?php $d = 4; // Set $d to 4. ?> Then another <?php echo $d; ?> Then another 4 C comments |
| 44 | While shell-style and C++-style comments are useful for annotating code or making short notes, longer comments require a different style. As such, PHP supports block comments whose syntax comes from the C programming language. When PHP en- counters a slash followed by an asterisk (/*), everything after that, until it encounters an asterisk followed by a slash (*/), is considered a comment. This kind of comment, unlike those shown earlier, can span multiple lines. Here’s an example of a C-style multiline comment: /* In this section, we take a bunch of variables and assign numbers to them. There is no real reason to do this, we're just having fun. */ $a = 1; $b = 2; $c = 3; $d = 4; |
| 45 | Because C-style comments have specific start and end markers, you can tightly integrate them with code. This tends to make your code harder to read and is discouraged: /* These comments can be mixed with code too, see? */ $e = 5; /* This works just fine. */ C-style comments, unlike the other types, continue past the end PHP tag markers. For example: <?php $l = 12; $m = 13; /* A comment begins here ?> <p>Some stuff you want to be HTML.</p> <?= $n = 14; ?> */ echo("l=$l m=$m n=$n "); ?><p>Now <b>this</b> is regular HTML...</p> l=12 m=13 n= <p>Now <b>this</b> is regular HTML...</p> You can indent comments as you like: /* There are no special indenting or spacing rules that have to be followed, either. */ C-style comments can be useful for disabling sections of code. In the following example, we’ve disabled the second and third statements, as well as the inline comment, by including them in a block comment. To enable the code, all we have to do is remove the comment markers: $f = 6; /* $g = 7; # This is a different style of comment $h = 8; |
| 46 | However, you have to be careful not to attempt to nest block comments: $i = 9; /* $j = 10; /* This is a comment */ $k = 11; Here is some comment text. */ In this case, PHP tries (and fails) to execute the (non)statement Here is some comment text and returns an error. |
| 47 | Literals A literal is a data value that appears directly in a program. The following are all literals in PHP: 2001 0xFE 1.4142 "Hello World" 'Hi' true null Identifiers An identifier is simply a name. In PHP, identifiers are used to name variables, functions, constants, and classes. The first character of an identifier must be an ASCII letter (up- percase or lowercase), the underscore character (_), or any of the characters between ASCII 0x7F and ASCII 0xFF. After the initial character, these characters and the digits 0–9 are valid. |
| 48 | Variable names Variable names always begin with a dollar sign ($) and are case-sensitive. Here are some valid variable names: $bill $head_count $MaximumForce $I_HEART_PHP $_underscore $_int Here are some illegal variable names: $not valid $| $3wa These variables are all different due to case sensitivity: $hot_stuff $Hot_stuff $hot_Stuff $HOT_STUFF |
| 49 | Function names Function names are not case-sensitive (functions are discussed in more detail in Chap- ter 3). Here are some valid function names: tally list_all_users deleteTclFiles LOWERCASE_IS_FOR_WIMPS _hide |
| 50 | These function names refer to the same function: howdy HoWdY HOWDY HOWdy howdy Class names Class names follow the standard rules for PHP identifiers and are also not case-sensitive. Here are some valid class names: Person account The class name stdClass is reserved. Constants A constant is an identifier for a simple value; only scalar values—Boolean, integer, double, and string—can be constants. Once set, the value of a constant cannot change. Constants are referred to by their identifiers and are set using the define() function: define('PUBLISHER', "O'Reilly & Associates"); echo PUBLISHER; |
| 51 | Keywords A keyword (or reserved word) is a word set aside by the language for its core function- ality—you cannot give a variable, function, class, or constant the same name as a key- word. Table 2-1 lists the keywords in PHP, which are case-insensitive. Table 2-1. PHP core language keywords __CLASS__ __DIR__ __FILE__ __FUNCTION__ __LINE__ __METHOD__ __NAMESPACE__ __TRAIT__ __halt_compiler() abstract and array() as break echo insteadof else interface elseif isset() empty() list() enddeclare namespace endfor new endforeach or endif print endswitch private endwhile protected eval() public exit() require extends require_once final return www.it-ebooks.info Lexical Structure | 21 callable for case foreach catch function class global clone goto const if continue implements declare include default include_once die() instanceof do static switch throw trait try unset() use var while xor |
| 52 | In addition, you cannot use an identifier that is the same as a built-in PHP function. For a complete list of these, see the Appendix. Data Types PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point numbers, strings, and Booleans. Two are compound (collec- tion) types: arrays and objects. The remaining two are special types: resource and NULL. Numbers, Booleans, resources, and NULL are discussed in full here, while strings, arrays, and objects are big enough topics that they get their own chapters (Chapters 4, 5, and 6). |
| 53 | Integers Integers are whole numbers, such as 1, 12, and 256. The range of acceptable values varies according to the details of your platform but typically extends from −2,147,483,648 to +2,147,483,647. Specifically, the range is equivalent to the range of the long data type of your C compiler. Unfortunately, the C standard doesn’t specify what range that long type should have, so on some systems you might see a different integer range. |
| 54 | Integer literals can be written in decimal, octal, or hexadecimal. Decimal values are represented by a sequence of digits, without leading zeros. The sequence may begin with a plus (+) or minus (−) sign. If there is no sign, positive is assumed. Examples of decimal integers include the following: 1998 −641 +33 |
| 55 | Octal numbers consist of a leading 0 and a sequence of digits from 0 to 7. Like decimal numbers, octal numbers can be prefixed with a plus or minus. Here are some example octal values and their equivalent decimal values: 0755 // decimal 493 +010 // decimal 8 Hexadecimal values begin with 0x, followed by a sequence of digits (0–9) or letters (A–F). The letters can be upper- or lowercase but are usually written in capitals. Like decimal and octal values, you can include a sign in hexadecimal numbers: 0xFF // decimal 255 0x10 // decimal 16 -0xDAD1 // decimal −56017 Binary numbers begin with 0b, followed by a sequence of digits (0 and 1). Like other values, you can include a sign in binary numbers: 0b01100000 0b00000010 -0b10 // decimal 1 // decimal 2 // decimal −2 If you try to store a variable that is too large to be stored as an integer or is not a whole number, it will automatically be turned into a floating-point number. Use the is_int() function (or its is_integer() alias) to test whether a value is an integer: if (is_int($x)) { // $x is an integer } |
| 56 | Floating-Point Numbers Floating-point numbers (often referred to as real numbers) represent numeric values with decimal digits. Like integers, their limits depend on your machine’s details. PHP floating-point numbers are equivalent to the range of the double data type of your C compiler. Usually, this allows numbers between 1.7E−308 and 1.7E+308 with 15 digits of accuracy. If you need more accuracy or a wider range of integer values, you can use the BC or GMP extensions. |
| 57 | PHP recognizes floating-point numbers written in two different formats. There’s the one we all use every day: 3.14 0.017 -7.1 but PHP also recognizes numbers in scientific notation: 0.314E1 // 0.314*10^1, or 3.14 17.0E-3 // 17.0*10^(-3), or 0.017 Floating-point values are only approximate representations of numbers. For example, on many systems 3.5 is actually represented as 3.4999999999. This means you must |
| 58 | Strings Because strings are so common in web applications, PHP includes core-level support for creating and manipulating strings. A string is a sequence of characters of arbitrary length. String literals are delimited by either single or double quotes: 'big dog' "fat hog" Variables are expanded (interpolated) within double quotes, while within single quotes they are not: $name = "Guido"; echo "Hi, $name "; echo 'Hi, $name'; Hi, Guido Hi, $name Double quotes also support a variety of string escapes, as listed in Table 2-2. Table 2-2. Escape sequences in double-quoted strings Escape sequence \" \r \t \\ \$ \{ \} \[ \] Character represented Double quotes Newline Carriage return Tab Backslash Dollar sign Left brace Right brace Left bracket Right bracket |
| 59 | Character represented ASCII character represented by octal value ASCII character represented by hex value |
| 60 | C:\WINDOWS\SYSTEM Tim O'Reilly To test whether two strings are equal, use the == (double equals) comparison operator: if ($a == $b) { echo "a and b are equal" } Use the is_string() function to test whether a value is a string: if (is_string($x)) { // $x is a string } PHP provides operators and functions to compare, disassemble, assemble, search, re- place, and trim strings, as well as a host of specialized string functions for working with HTTP, HTML, and SQL encodings. Because there are so many string-manipulation functions, we’ve devoted a whole chapter (Chapter 4) to covering all the details. |
| 61 | Booleans A Boolean value represents a “truth value”—it says whether something is true or not. Like most programming languages, PHP defines some values as true and others as false. Truth and falseness determine the outcome of conditional code such as: if ($alive) { ... } In PHP, the following values all evaluate to false: • The keyword false • The integer 0 • The floating-point value 0.0 • The empty string ("") and the string "0" • An array with zero elements • An object with no values or functions • The NULL value |
| 62 | A value that is not false is true, including all resource values (which are described later in the section “Resources” on page 28). PHP provides true and false keywords for clarity: $x = 5; $x = true; $y = ""; $y = false; // $x has a true value // clearer way to write it // $y has a false value // clearer way to write it Use the is_bool() function to test whether a value is a Boolean: if (is_bool($x)) { // $x is a Boolean } |
| 63 | Arrays An array holds a group of values, which you can identify by position (a number, with zero being the first position) or some identifying name (a string), called an associative index: $person[0] = "Edison"; $person[1] = "Wankel"; $person[2] = "Crapper"; $creator['Light bulb'] = "Edison"; $creator['Rotary Engine'] = "Wankel"; $creator['Toilet'] = "Crapper"; The array() construct creates an array. Here are two examples: $person = array("Edison", "Wankel", "Crapper"); $creator = array('Light bulb' => "Edison", 'Rotary Engine' => "Wankel", 'Toilet' => "Crapper"); |
| 64 | There are several ways to loop through arrays, but the most common is a foreach loop: foreach ($person as $name) { echo "Hello, {$name} "; } foreach ($creator as $invention => $inventor) { echo "{$inventor} created the {$invention} "; } Hello, Edison Hello, Wankel Hello, Crapper Edison created the Light bulb Wankel created the Rotary Engine Crapper created the Toilet |
| 65 | You can sort the elements of an array with the various sort functions: sort($person); // $person is now array("Crapper", "Edison", "Wankel") asort($creator); // $creator is now array('Toilet' => "Crapper", // 'Light bulb' => "Edison", // 'Rotary Engine' => "Wankel"); Use the is_array() function to test whether a value is an array: if (is_array($x)) { // $x is an array } |
| 66 | There are functions for returning the number of items in the array, fetching every value in the array, and much more. Arrays are covered in-depth in Chapter 5. Objects PHP also supports object-oriented programming (OOP). OOP promotes clean modular design, simplifies debugging and maintenance, and assists with code reuse. PHP 5 has a new and improved OOP approach that we cover in Chapter 6. Classes are the building blocks of object-oriented design. A class is a definition of a structure that contains properties (variables) and methods (functions). Classes are de- fined with the class keyword: class Person { public $name = ''; function name ($newname = NULL) { if (!is_null($newname)) { $this->name = $newname; } return $this->name; } } |
| 67 | Once a class is defined, any number of objects can be made from it with the new key- word, and the object’s properties and methods can be accessed with the -> construct: $ed = new Person; $ed->name('Edison'); echo "Hello, {$ed->name} "; $tc = new Person; $tc->name('Crapper'); echo "Look out below {$tc->name} "; |
| 68 | Use the is_object() function to test whether a value is an object: if (is_object($x)) { // $x is an object } Chapter 6 describes classes and objects in much more detail, including inheritance, encapsulation, and introspection. Resources Many modules provide several functions for dealing with the outside world. For ex- ample, every database extension has at least a function to connect to the database, a function to send a query to the database, and a function to close the connection to the database. Because you can have multiple database connections open at once, the con- nect function gives you something by which to identify that unique connection when you call the query and close functions: a resource (or a “handle”). Each active resource has a unique identifier. Each identifier is a numerical index into an internal PHP lookup table that holds information about all the active resources. PHP maintains information about each resource in this table, including the number of ref- erences to (or uses of) the resource throughout the code. When the last reference to a resource value goes away, the extension that created the resource is called to free any memory, close any connection, etc., for that resource: $res = database_connect(); // fictitious database connect function database_query($res); $res = "boo"; |
| 69 | // database connection automatically closed because $res is redefined The benefit of this automatic cleanup is best seen within functions, when the resource is assigned to a local variable. When the function ends, the variable’s value is reclaimed by PHP: function search() { $res = database_connect(); database_query($res); } When there are no more references to the resource, it’s automatically shut down. That said, most extensions provide a specific shutdown or close function, and it’s con- sidered good style to call that function explicitly when needed rather than to rely on variable scoping to trigger resource cleanup. Use the is_resource() function to test whether a value is a resource: if (is_resource($x)) { // $x is a resource } |
| 70 | Callbacks Callbacks are functions or object methods used by some functions, such as call_user_func(). Callbacks can also be created by the create_function() method and through closures (described in Chapter 3): $callback = function myCallbackFunction() { echo "callback achieved"; } call_user_func($callback); callback achieved NULL |
| 71 | There’s only one value of the NULL data type. That value is available through the case- insensitive keyword NULL. The NULL value represents a variable that has no value (similar to Perl’s undef or Python’s None): $aleph = "beta"; $aleph = null; $aleph = Null; $aleph = NULL; // variable's value is gone // same // same Use the is_null() function to test whether a value is NULL—for instance, to see whether a variable has a value: if (is_null($x)) { // $x is NULL } |
| 72 | Variables Variables in PHP are identifiers prefixed with a dollar sign ($). For example: $name $Age $_debugging $MAXIMUM_IMPACT A variable may hold a value of any type. There is no compile-time or runtime type checking on variables. You can replace a variable’s value with another of a different type: $what = "Fred"; $what = 35; $what = array("Fred", 35, "Wilma"); |
| 73 | There is no explicit syntax for declaring variables in PHP. The first time the value of a variable is set, the variable is created. In other words, setting a value to a variable also functions as a declaration. For example, this is a valid complete PHP program: $day = 60 * 60 * 24; echo "There are {$day} seconds in a day. "; There are 86400 seconds in a day. A variable whose value has not been set behaves like the NULL value: if ($uninitializedVariable === NULL) { echo "Yes!"; } Yes! |
| 74 | Variable Variables You can reference the value of a variable whose name is stored in another variable by prefacing the variable reference with an additional dollar sign ($). For example: $foo = "bar"; $$foo = "baz"; After the second statement executes, the variable $bar has the value "baz". Variable References In PHP, references are how you create variable aliases. To make $black an alias for the variable $white, use: $black =& $white; |
| 75 | The old value of $black, if any, is lost. Instead, $black is now another name for the value that is stored in $white: $bigLongVariableName = "PHP"; $short =& $bigLongVariableName; $bigLongVariableName .= " rocks!"; print "\$short is $short "; print "Long is $bigLongVariableName "; $short is PHP rocks! Long is PHP rocks! $short = "Programming $short"; print "\$short is $short "; print "Long is $bigLongVariableName "; |
| 76 | After the assignment, the two variables are alternate names for the same value. Unset- ting a variable that is aliased does not affect other names for that variable’s value, however: $white = "snow"; $black =& $white; unset($white); print $black; snow Functions can return values by reference (for example, to avoid copying large strings or arrays, as discussed in Chapter 3): function &retRef() { $var = "PHP"; return $var; } $v =& retRef(); Variable Scope // note the & // note the & The scope of a variable, which is controlled by the location of the variable’s declaration, determines those parts of the program that can access it. There are four types of variable scope in PHP: local, global, static, and function parameters. |
| 77 | Local scope A variable declared in a function is local to that function. That is, it is visible only to code in that function (including nested function definitions); it is not accessible outside the function. In addition, by default, variables defined outside a function (called global variables) are not accessible inside the function. For example, here’s a function that updates a local variable instead of a global variable: function updateCounter() { $counter++; } $counter = 10; updateCounter(); echo $counter; The $counter inside the function is local to that function, because we haven’t said otherwise. The function increments its private $counter variable, which is destroyed when the subroutine ends. The global $counter remains set at 10. |
| 78 | Only functions can provide local scope. Unlike in other languages, in PHP you can’t create a variable whose scope is a loop, conditional branch, or other type of block. Global scope Variables declared outside a function are global. That is, they can be accessed from any part of the program. However, by default, they are not available inside functions. To allow a function to access a global variable, you can use the global keyword inside the function to declare the variable within the function. Here’s how we can rewrite the updateCounter() function to allow it to access the global $counter variable: function updateCounter() { global $counter; $counter++; } $counter = 10; updateCounter(); echo $counter; |
| 79 | A more cumbersome way to update the global variable is to use PHP’s $GLOBALS array instead of accessing the variable directly: function updateCounter() { $GLOBALS[counter]++; } $counter = 10; updateCounter(); echo $counter; |
| 80 | Static variables A static variable retains its value between calls to a function but is visible only within that function. You declare a variable static with the static keyword. For example: function updateCounter() { static $counter = 0; $counter++; echo "Static counter is now {$counter} "; } $counter = 10; updateCounter(); updateCounter(); |
| 81 | echo "Global counter is {$counter} "; Static counter is now 1 Static counter is now 2 Global counter is 10 Function parameters As we’ll discuss in more detail in Chapter 3, a function definition can have named parameters: function greet($name) { echo "Hello, {$name} "; } greet("Janet"); Hello, Janet Function parameters are local, meaning that they are available only inside their func- tions. In this case, $name is inaccessible from outside greet(). |
Комментарии