1. Trang chủ
  2. » Công Nghệ Thông Tin

Phát triển web với PHP và MySQL - p 16 doc

10 219 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 545,79 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Calling Functions The following line is the simplest possible call to a function: function_name; This calls a function named function_namethat does not require parameters.. This function

Trang 1

LISTING 5.3 header.inc—The Reusable Header for All TLA Web Pages

<html>

<head>

<title>TLA Consulting Pty Ltd</title>

<style>

h1 {color:white; font-size:24pt; text-align:center;

font-family:arial,sans-serif}

.menu {color:white; font-size:12pt; text-align:center;

font-family:arial,sans-serif; font-weight:bold}

td {background:black}

p {color:black; font-size:12pt; text-align:justify;

font-family:arial,sans-serif}

p.foot {color:white; font-size:9pt; text-align:center;

font-family:arial,sans-serif; font-weight:bold}

a:link,a:visited,a:active {color:white}

</style>

</head>

<body>

<! page header >

<table width=”100%” cellpadding = 12 cellspacing =0 border = 0>

<tr bgcolor = black>

<td align = left><img src = “logo.gif”></td>

<td>

<h1>TLA Consulting</h1>

</td>

<td align = right><img src = “logo.gif”></td>

</tr>

</table>

<! menu >

<table width = “100%” bgcolor = white cellpadding = 4 cellspacing = 4>

<tr >

<td width = “25%”>

<img src = “s-logo.gif”> <span class=menu>Home</span></td>

<td width = “25%”>

<img src = “s-logo.gif”> <span class=menu>Contact</span></td>

<td width = “25%”>

<img src = “s-logo.gif”> <span class=menu>Services</span></td>

<td width = “25%”>

<img src = “s-logo.gif”> <span class=menu>Site Map</span></td>

</tr>

</table>

5

Trang 2

L ISTING 5.4 footer.inc—The Reusable Footer for All TLA Web Pages

<! page footer >

<table width = “100%” bgcolor = black cellpadding = 12 border = 0>

<tr>

<td>

<p class=foot>&copy; TLA Consulting Pty Ltd.</p>

<p class=foot>Please see our

<a href =”legal.php3”>legal information page</a></p>

</td>

</tr>

</table>

</body>

</html>

This approach gives you a consistent looking Web site very easily, and you can make a new page in the same style by typing something like:

<? require(“header.inc”); ?>

Here is the content for this page

<? require(“footer.inc”); ?>

Most importantly, even after we have created many pages using this header and footer, it is easy to change the header and footer files Whether you are making a minor text change, or completely redesigning the look of the site, you only need to make the change once We do not need to separately alter every page in the site because each page is loading in the header and footer files

The example shown here only uses plain HTML in the body, header and footer This need not

be the case Within these files, we could use PHP statements to dynamically generate parts of the page

Using auto_prepend_file and auto_append_file

If we want to use require()to add our header and footer to every page, there is another way

we can do it Two of the configuration options in the php.ini file are auto_prepend_fileand

auto_append_file By setting these to our header and footer files, we ensure that they will be loaded before and after every page

For Windows, the settings will resemble the following:

auto_prepend_file = “c:/inetpub/include/header.inc”

auto_append_file = “c:/inetpub/include/footer.inc”

For UNIX, they will resemble the following:

auto_prepend_file = “/home/username/include/header.inc”

auto_append_file = “/home/username/include/footer.inc”

Trang 3

If we use these directives, we do not need to typerequire()statements, but the headers and

footers will no longer be optional on pages

If you are using an Apache Web server, you can change various configuration options like

these for individual directories To do this, your server must be set up to allow its main

config-uration file(s) to be overridden To set up auto prepending and appending for a directory, create

a file called .htaccessin the directory The file needs to contain the following two lines:

php_value auto_prepend_file “/home/username/include/header.inc”

php_value auto_append_file “/home/username/include/footer.inc”

Note that the syntax is slightly different from the same option in php.ini, as well as php_value

at the start of the line: There is no equal sign A number of other php.ini configuration settings

can be altered in this way too

This syntax changed from PHP 3 If you are using an old version, the lines in your htaccess

file should resemble this:

php3_auto_prepend_file /home/username/include/header.inc

php3_auto_append_file /home/username/include/footer.inc

Setting options in the .htaccessfile rather than in either php.ini or your Web server’s

configu-ration file gives you a lot of flexibility You can alter settings on a shared machine that only

affect your directories You do not need to restart the Web server, and you do not need

adminis-trator access A drawback to the .htaccessmethod is that the files are read and parsed each

time a file in that directory is requested rather than just once at startup, so there is a

perfor-mance penalty

Using include()

The statements require()and include()are very similar, but some important differences

exist in the way they work

An include()statement is evaluated each time the statement is executed, and not evaluated at

all if the statement is not executed A require()statement is executed the first time the

state-ment is parsed, regardless of whether the code block containing it will be executed

Unless your server is very busy, this will make little difference but it does mean that code with

require()statements inside conditional statements is inefficient

if($variable == true)

{

require(“file1.inc”);

}

else

{

require(“file2.inc”);

}

5

Trang 4

This code will needlessly load both files every time the script is run, but only use one depend-ing on the value of $variable However, if the code had been written using two include()

statements, only one of the files would be loaded and used as in the following version:

if($variable == true) {

include(“file1.inc”);

} else { include(“file2.inc”);

}

Unlike files loaded via a require()statement, files loaded via an include()can return a value Therefore, we can notify other parts of the program about a success or failure in the included file, or return an answer or result

We might decide that we are opening files a lot and rather than retyping the same lines of code every time, we want an include file to open them for us Our include file might be called

“openfile.inc” and resemble the following:

<?

@ $fp = fopen($name, $mode);

if (!$fp) {

echo “<p><strong> Oh No! I could not open the file.</strong></p>”;

return 0;

} else { return 1;

}

?>

This file will try to open the file named $nameusing the mode given by $mode If it fails, it will give an error message and return 0 If it succeeds, it will return 1 and generate no output

We can call this file in a script as follows:

$name = “file.txt”;

$mode = “r”;

$result = include(“openfile.php”);

if( $result == 1 ) {

// do what we wanted to do with the file // refer to $fp created in the include file }

Trang 5

Note that we can create variables in the main file or in the included or required file, and the

variable will exist in both This behavior is the same for both require()and include()

state-ments

You cannot use require()in exactly the way shown here because you cannot return values

from require()statements Returning a value can be useful because it enables you to notify

later parts of your program about a failure, or to do some self-contained processing and return

an answer Functions are an even better vehicle than included files for breaking code into

self-contained modules We will look at functions next

If you are wondering why, given the advantages of include()over require(), you would ever

use require(), the answer is that it is slightly faster

Using Functions in PHP

Functions exist in most programming languages They are used to separate code that performs

a single, well-defined task This makes the code easier to read and allows us to reuse the code

each time we need to do the same task

A function is a self-contained module of code that prescribes a calling interface, performs

some task, and optionally returns a result

You have seen a number of functions already In preceding chapters, we have routinely called a

number of the functions that come built-in to PHP We have also written a few simple functions

but glossed over the details In this section, we will cover calling and writing functions in more

detail

Calling Functions

The following line is the simplest possible call to a function:

function_name();

This calls a function named function_namethat does not require parameters This line of code

ignores any value that might be returned by this function

A number of functions are called in exactly this way The function phpinfo()is often useful in

testing because it displays the installed version of PHP, information about PHP, the Web server

set-up, and the values of various PHP and server variables This function does not take any

parameters, and we generally ignore its return value, so a call to phpinfo()will resemble the

following:

phpinfo();

5

Trang 6

Most functions do require one or more parameters—information given to a function when it is called that influences the outcome of executing the function We pass parameters by placing the data or the name of a variable holding the data inside parentheses after the function name

A call to a function with a parameter resembles the following:

function_name(“parameter”);

In this case, the parameter we used was a string containing only the word parameter, but the following calls are also fine depending on the function:

function_name(2);

function_name(7.993);

function_name($variable);

In the last line,$variablemight be any type of PHP variable, including an array

A parameter can be any type of data, but particular functions will usually require particular data types

You can see how many parameters a function takes, what each represents, and what data type

each needs to be from the function’s prototype We often show the prototype when we describe

a function, but you can find a complete set of function prototypes for the PHP function library

at http://www.php.net This is the prototype for the function fopen():

int fopen( string filename, string mode, [int use_include_path] );

The prototype tells us a number of things, and it is important that you know how to correctly interpret these specifications In this case, the word intbefore the function name tells us that this function will return an integer The function parameters are inside the parentheses In the case of fopen(), three parameters are shown in the prototype The parameter filename and mode are strings and the parameter is an integer

The square brackets around use_include_pathindicate that this parameter is optional We can provide values for optional parameters or we can choose to ignore them, and the default value will be used

After reading the prototype for this function, we know that the following code fragment will be

a valid call to fopen():

$name = “myfile.txt”;

$openmode = “r”;

$fp = fopen($name, $openmode)

This code calls the function named fopen() The value returned by the function will be stored

in the variable $fp We chose to pass to the function a variable called $namecontaining a string

Trang 7

representing the file we want to open, and a variable called $openmodecontaining a string

rep-resenting the mode in which we want to open the file We chose not to provide the optional

third parameter

Call to Undefined Function

If you attempt to call a function that does not exist, you will get an error message as shown in

Figure 5.3

5

F IGURE 5.3

This error message is the result of calling a function that does not exist.

The error messages that PHP gives are usually very useful This one tells us exactly in which

file the error occurred, in which line of the script it occurred, and the name of the function we

attempted to call This should make it fairly easy to find and correct

There are two things to check if you see this error message:

1 Is the function name spelled correctly?

2 Does the function exist in the version of PHP you are using?

It is not always easy to remember how a function name is spelled For instance, some

two-word function names have an underscore between the two-words and some do not The function

stripslashes()runs the two words together, whereas the function strip_tags()separates

the words with an underscore Misspelling the name of a function in a function call results in

an error as shown in Figure 5.3

Many functions used in this book do not exist in PHP 3.0 because this book assumes that you

are using at least PHP 4.0 In each new version, new functions are defined and if you are using

an older version, the added functionality and performance justify an upgrade To see when a

particular function was added, you can see the online manual at www.php.net Attempting to

call a function that is not declared in the version you are running will result in an error such as

the one shown in Figure 5.3

Trang 8

Case and Function Names

Note that calls to functions are not case sensitive, so calling function_name(),

Function_Name(), or FUNCTION_NAME()are all valid and will all have the same result You are free to capitalize in any way you find easy to read, but you should aim to be consistent The convention used in this book, and most other PHP documentation, is to use all lowercase

It is important to note that function names behave differently to variable names Variable

names are case sensitive, so $Nameand $nameare two separate variables, but Name()and

name()are the same function

In the preceding chapters, you have seen many examples using some of PHP’s built-in func-tions However, the real power of a programming language comes from being able to create your own functions

Why Should You Define Your Own Functions?

The functions built in to PHP enable you to interact with files, use a database, create graphics, and connect to other servers However, in your career there will be many times when you will need to do something that the language’s creators did not foresee

Fortunately, you are not limited to using the built-in functions because you can write your own

to perform any task that you like Your code will probably be a mixture of existing functions combined with your own logic to perform a task for you If you are writing a block of code for

a task that you are likely to want to reuse in a number of places in a script or in a number of scripts, you would be wise to declare that block as a function

Declaring a function allows you to use your own code in the same way as the built-in func-tions You simply call your function and provide it with the necessary parameters This means that you can call and reuse the same function many times throughout your script

Basic Function Structure

A function declaration creates or declares a new function The declaration begins with the

key-word function, provides the function name, the parameters required, and contains the code that will be executed each time this function is called

Here is the declaration of a trivial function:

function my_function() {

echo “My function was called”;

}

Trang 9

This function declaration begins with function, so that human readers and the PHP parser

know that what follows will be a user-defined function The function name is my_function

We can call our new function with the following statement:

my_function();

As you probably guessed, calling this function will result in the text “My function was

called.”appearing in the viewer’s browser

Built-in functions are available to all PHP scripts, but if you declare your own functions, they

are only available to the script(s) in which they were declared It is a good idea to have one file

containing your commonly used functions You can then have a require()statement in all

your scripts to make your functions available

Within a function, curly braces enclose the code that performs the task you require Between

these braces, you can have anything that is legal elsewhere in a PHP script including function

calls, declarations of new variables or functions,require()or include()statements, and

plain HTML If we want to exit PHP within a function and type plain HTML, we do it the

same way as anywhere else in the script—with a closing PHP tag followed by the HTML The

following is a legal modification of the previous example and produces the same output:

<?

function my_function()

{

?>

My function was called

<?

}

?>

Note that the PHP code is enclosed within matching opening and closing PHP tags For most

of the small code fragment examples in this book, we do not show these tags They are shown

here because they are required within the example as well as above and below it

Naming Your Function

The most important thing to consider when naming your functions is that the name should be

short but descriptive If your function creates a page header,pageheader()or page_header()

might be good names

A few restrictions are as follows:

• Your function cannot have the same name as an existing function

• Your function name can only contain letters, digits, and underscores

• Your function name cannot begin with a digit

5

Trang 10

Many languages do allow you to reuse function names This feature is called function

over-loading However, PHP does not support function overloading, so your function cannot have

the same name as any built-in function or an existing user-defined function Note that although every PHP script knows about all the built-in functions, user-defined functions only exist in scripts where they are declared This means that you could reuse a function name in a different file, but this would lead to confusion and should be avoided

The following function names are legal:

name() name2() name_three() _namefour()

These are illegal:

5name() name-six() fopen()

(The last would be legal if it didn’t already exist.)

Parameters

In order to do their work, most functions require one or more parameters A parameter allows you to pass data into a function Here is an example of a function that requires a parameter This function takes a one-dimensional array and displays it as a table

function create_table($data) {

echo “<table border = 1>”;

reset($data); // Remember this is used to point to the beginning

$value = current($data);

while ($value) {

echo “<tr><td>$value</td></tr>\n”;

$value = next($data);

} echo “</table>”;

}

If we call our create_table()function as follows:

$my_array = array(“Line one.”,”Line two.”,”Line three.”);

create_table($my_array);

we will see output as shown in Figure 5.4

Ngày đăng: 06/07/2014, 19:20