• Tidak ada hasil yang ditemukan

File Inclusion Statements

Dalam dokumen Beginning PHP and MySQL 5 (Halaman 121-126)

<?php

$primes = array(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47);

for($count = 1; $count++; $count < 1000) { $randomNumber = rand(1,50);

if (in_array($randomNumber,$primes)) { break;

} else {

echo "<p>Non-prime number encountered: $randomNumber</p>";

} }

?>

Sample output follows:

Non-prime number encountered: 48 Non-prime number encountered: 42 Prime number encountered: 17

continue

The continue statement causes execution of the current loop iteration to end and commence at the beginning of the next iteration. For example, execution of the following while body will recommence if $usernames[$x] is found to have the value “missing”:

<?php

$usernames = array("grace","doris","gary","nate","missing","tom");

for ($x=0; $x < count($usernames); $x++) { if ($usernames[$x] == "missing") continue;

echo "Staff member: $usernames[$x] <br />";

}

?>

This results in the following output:

Staff member: grace Staff member: doris Staff member: gary Staff member: nate Staff member: tom

include()

include (/path/to/filename)

The include() statement will evaluate and include a file into the location where it is called.

Including a file produces the same result as copying the data from the file specified into the location in which the statement appears.

Like the print and echo statements, you have the option of omitting the parentheses when using include(). For example, if you wanted to include a series of predefined functions and configuration variables, you could place them into a separate file (called init.php, for example), and then include that file within the top of each PHP script, like this:

<?php

include "/usr/local/lib/php/wjgilmore/init.php";

/* the script continues here */

?>

You can also execute include() statements conditionally. For example, if an include() statement is placed in an if statement, the file will be included only if the if statement in which it is enclosed evaluates to true. One quirk regarding the use of include() in a conditional is that it must be enclosed in statement block curly brackets or in the alternative statement enclosure. Consider the difference in syntax between the following two code snippets. The first presents incorrect use of conditional include() statements due to the lack of proper block enclosures:

<?php

if (expression)

include ('filename');

else

include ('another_filename');

?>

The next snippet presents the correct use of conditional include() statements by properly enclosing the blocks in curly brackets:

<?php

if (expression) { include ('filename');

} else {

include ('another_filename');

}

?>

One misconception about the include() statement is the belief that, because the included code will be embedded in a PHP execution block, the PHP escape tags aren’t required. However, this is not so; the delimiters must always be included. Therefore, you could not just place a PHP command in a file and expect it to parse correctly, such as the one found here:

print "this is an invalid include file";

Instead, any PHP statements must be enclosed with the correct escape tags, as shown here:

<?php

print "this is an invalid include file";

?>

Tip

Any code found within an included file will inherit the variable scope of the location of its caller.

Interestingly, all include() statements support the inclusion of files residing on remote servers by prefacing include()’s argument with a supported URL. If the resident server is PHP- enabled, any variables found within the included file can be parsed by passing the necessary key/value pairs as would be done in a GET request, like this:

include "http://www.wjgilmore.com/index.html?background=blue";

Two requirements must be satisfied before the inclusion of remote files is possible. First, the allow_url_fopen configuration directive must be enabled. Second, the URL wrapper must be supported. The latter requirement is discussed in further detail in Chapter 16.

include_once()

include_once (filename)

The include_once() function has the same purpose as include(), except that it first verifies whether or not the file has already been included. If it has been, include_once() will not execute.

Otherwise, it will include the file as necessary. Other than this difference, include_once() operates in exactly the same way as include().

The same quirk pertinent to enclosing include() within conditional statements also applies to include_once().

require()

require (filename)

For the most part, require() operates like include(), including a template into the file in which the require() call is located.

There are two important differences between require() and include(). First, the file will be included in the script in which the require() construct appears, regardless of where require() is located. For instance, if require() were placed within an if statement that evaluated to false, the file would be included anyway!

Tip

A URL can be used with require() only if allow_url_fopen is enabled, which by default it is.

The second important difference is that script execution will stop if a require() fails, whereas it may continue in the case of an include(). One possible explanation for the failure of a require() statement is an incorrectly referenced target path.

require_once()

require_once (insertion_file)

As your site grows, you may find yourself redundantly including certain files. Although this might not always be a problem, sometimes you will not want modified variables in the included file to be overwritten by a later inclusion of the same file. Another problem that arises is the clashing of function names should they exist in the inclusion file. You can solve these problems with the require_once() function.

The require_once() function ensures that the inclusion file is included only once in your script. After require_once() is encountered, any subsequent attempts to include the same file will be ignored.

Other than the verification procedure of require_once(), all other aspects of the function are the same as for require().

Summary

Although the material presented here is not as glamorous as the material in later chapters, it is invaluable to your success as a PHP programmer, because all subsequent functionality is based on these building blocks. This will soon become apparent.

The next chapter is devoted to the construction and invocation of functions, reusable chunks of code intended to perform a specific task. This material starts you down the path necessary to begin building modular, reusable PHP applications.

91

■ ■ ■

Functions

E

ven in trivial applications, repetitive processes are likely to exist. For nontrivial applications, such repetition is a given. For example, in an e-commerce application, you might need to query a customer’s profile information numerous times: at login, at checkout, and when verifying a shipping address. However, repeating the profile querying process throughout the application would be not only error-prone, but also a nightmare to maintain. What happens if a new field has been added to the customer’s profile? You might need to sift through each page of the application, modifying the query as necessary, likely introducing errors in the process.

Thankfully, the concept of embodying these repetitive processes within a named section of code, and then invoking this name as necessary, has long been a key component of any respectable computer language. These sections of code are known as functions, and they grant you the convenience of a singular point of modification if the embodied process requires changes in the future, which greatly reduces both the possibility of programming errors and maintenance overhead. In this chapter, you’ll learn all about PHP functions, including how to create and invoke them, pass input, return both single and multiple values to the caller, and create and include function libraries. Additionally, you’ll learn about both recursive and variable functions.

Dalam dokumen Beginning PHP and MySQL 5 (Halaman 121-126)