PHP and MySQL Web Development - P33 pptx

5 295 0
PHP and MySQL Web Development - P33 pptx

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

Thông tin tài liệu

127 Using require() for Web Site Templates require('file2.inc'); } This code will needlessly load both files every time the script is run, but only use one depending 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 follow- ing 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: <?php @ $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 $name using 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 ) { 07 525x ch05 1/24/03 3:36 PM Page 127 128 Chapter 5 Reusing Code and Writing Functions // do what we wanted to do with the file // refer to $fp created in the include file } 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() statements. 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. As we mentioned before, this behaviour has now changed, so you can simply avoid the issue by upgrading to a newer version of PHP. Using Functions in PHP Functions exist in most programming languages.They are used to separate code that per- forms 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, per- forms some task, and optionally returns a result. You have seen a number of functions already. In preceding chapters, we have routine- ly 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_name that 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(); 07 525x ch05 1/24/03 3:36 PM Page 128 129 Using Functions in PHP 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 parame- ters 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, $variable might be any type of PHP variable, including an array. A parameter can be any type of data, but particular functions will usually require par- ticular 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. 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 int before 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_path indicate that this parameter is option- al.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 frag- ment 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 $name con- taining a string representing the file we want to open, and a variable called $openmode containing a string representing the mode in which we want to open the file. We chose not to provide the optional third parameter. 07 525x ch05 1/24/03 3:36 PM Page 129 130 Chapter 5 Reusing Code and Writing Functions 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. Figure 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 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 func- tion 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 check the online manu- al. 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. 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 07 525x ch05 1/24/03 3:36 PM Page 130 131 Basic Function Structure 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. Va r iable names are case sensitive, so $Name and $name are 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 functions. 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 functions.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 keyword 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'; } 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. 07 525x ch05 1/24/03 3:36 PM Page 131 . 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. of PHP. Using Functions in PHP Functions exist in most programming languages.They are used to separate code that per- forms a single, well-defined task.This makes the code easier to read and. routine- ly 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

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

Mục lục

    PHP and MySQL Web Development

    Part I: Using PHP

    Chapter 1: PHP Crash Course

    Chapter 2: Storing and Retrieving Data

    Chapter 4: String Manipulation and Regular Expressions

    Chapter 5: Reusing Code and Writing Functions

    Part II: Using MySQL

    Chapter 7: Designing Your Web Database

    Chapter 8: Creating Your Web Database

    Chapter 9: Working with Your MySQL Database

Tài liệu cùng người dùng

Tài liệu liên quan