Definition and application of functions
Key points of this chapter
2 Use built-in PHP functions
2 Browse online function manual
2 User-defined functions
2 Purchase skills: variable parameters, parameters Reference calls and variable functions
Any programming language has some kind of program abstraction processing capability (procedural abstraction, which is to name a certain section of program code so that it can be accessed when writing other program code sections). Some script languages lack this capability, and in our experience this can quickly make complex server-side code unmanageable.
The mechanism used by PHP to provide this abstract processing is the function. There are actually two types of functions in PHP, one that is already built into the language by PHP developers, and the other that is defined by each PHP programmer.
In this chapter, we take a look at how to use the large number of functions provided by PHP, and then learn how to define your own functions. Fortunately, there is no difference between using built-in functions and defining your own.
Using functions
The basic syntax for using (or calling) functions is as follows:
function_name(expression_1, expression_2,…,expression_n)
It is the function name followed by parentheses and commas separated by input operations formula, the form of a list (called function parameters) appears. According to the specific definition, the calling function can take no parameters, or can bring in multiple parameters at the same time.
When PHP encounters a function call, it first evaluates each parameter operation, and then uses these values as input to the function. After the function is executed, the return value (if there is a return value) is the result of the entire function expression.
The examples listed below are all valid calling methods of PHP's built-in functions:
sqtr(9) //Square root function, the result is "3"
rand(10,10+10) / /Return a value between "10" and "20"
strlen("This has 22 characters") //Return the value "22"
pi() //Return the approximate value of p
These functions are called with 1, 2, 1 and 0 arguments respectively.
Return values and side effects
Each function call is considered a PHP operation (like other operations). There are only two reasons to include functions in program code: to get the return value, or to get Side effects.
The return value of the function is the value of the function operation. You can use this value just like the evaluation result of any other operation. For example, you can assign it to a variable as follows:
$my_pi = pi();
Or, you can embed it in a complex In the operation formula, it is as follows:
$approx = sprt($approx)* sqrt($approx)
The function can also be used to achieve various side effects, including writing data to files , database operations, and displaying content output in the browser window. It is possible to use callbacks and side effects at the same time. For example, we often use a function with side effects and return a value at the same time to check whether the function is executing normally
.
The result of a function can be of any type. The array type is usually used as a function that returns multiple values.
Function Manual
PHP’s architecture is designed very smartly, making it easy to be extended by other developers. The original PHP language itself is easy to understand and very flexible. Most PHP functions exist in a large number of built-in functions. This means that developers are free to add new built-in functions and contribute to PHP, which is great because it doesn't change any part of PHP that users may depend on.
Although this book covers many built-in functions and explains some of them in more detail than the online manual, the manual provided at http://www.php.net still contains function information important reference resources. In this book, we will expand on the topics we want to excerpt to some extent, but the content of the PHP Manual remains the most complete reference on every aspect of PHP. While we hope to keep this book up to date with future versions of PHP, the online guide will provide the latest information on new PHP features, including those that are still under development. So it is very helpful to take a look at the PHP official website and the different resources provided online when you have time.
Although the following information is correct at the time of finalization of this book (the second edition was republished in 2002). However, some details may be outdated or no longer applicable due to updated versions or reorganization of the online manual.
If you want to search for online manuals, you can go to the http://www.php.net website and select the "documentaion" option label in the upper right navigation bar. This will redirect you to a directory containing various formats and user manual information. the link to. What we want to see is the annotated manual (currently linked to the View Online option on the Documentation page), which allows users to post their own annotation data to each page. [Please note: the manual annotation system is not the place to post questions! If you have questions about how to use it, check the mailing list section, which is located in the "support" tab of www.php.net, or refer to Appendix D of this book for PHP resources. The manual annotation system is a place where users can explain and put forward opinions in their own words after understanding it. However, it is indeed a way for us to contribute. This may also become an official version in the future. This is indeed our It's a great way to contribute, and it's also a great place to point out confusion and possible problems, but it's all in "English"! ]
Most of the user manual is test material for functions, and each built-in function has a separate description page. Each page begins with the function name and a single-line description, then a C-style function header declaration (explained in the next section), followed by a slightly longer description, maybe an example or two, and then (in Notes Manual) are comments and opinion reports from users.
Headers in the manual
For those who are not familiar with C language function headers, the very beginning of the function manual may be confusing. The basic format is:
return-type function-name(type argl,type2 arg2,…);
It indicates the expected function to return a value type value, function name and expected parameter type, etc.
The following is a basic header description:
string substr (string string,int startl [,int length]);
This means that the function substr will return a string and expects to get a string and two Integers are parameters. In fact, the square brackets on both sides of length indicate that this parameter is optional, so when calling substr, you can bring a string string and an int integer, or a string string and two int integers.
Unlike in C, the parameter types declared in these manual headers are not strictly necessary. If you call substr with a number as an argument, no error will occur; PHP converts the first argument to a string before starting to execute the function. However, the parameter type does reflect the original intention of the function creator. In addition, it is best to use the function according to the type specified in the manual, or to have sufficient understanding of type conversion matters, so as to ensure that expected result.
Generally speaking, the type name used in function manuals is one of the six basic types, or their aliases: integet (or int), double (or float, real), Boolean, string, array , object, resource and NULI. In addition, you can see the types of void and mixed. The Viod type function does not return any value at all, and the mixed parameter type means that the parameters can be of any type.
Search function manual
What is the best way to query information about a function in the manual? It mainly depends on your curiosity and what kind of part you are interested in? The most common question about functions is:
I want to use the X function, how should I use it?
I need to complete a certain Y task. Is there a function that can help me complete this task?
For the first case, the full version of the online manual provides automatic query based on the function name. Under the navigation bar on the upper right, the default search mode of the "search for" text box is the name of the function, and after the function is found, the web page that displays the function will be displayed (you can also select other search objects, including the entire The website's mailing list, this is a good place to search when you don't know the name of the function you need, but you can guess the rough name of the function you need).
If you are looking for it in the second case, it is best to use the hierarchical organization structure of the Function Reference (Funcrion Reference, one of the articles in the PHP manual), which is divided into 108 chapters. For example, the substr function mentioned earlier is in the "String functions" section within the "Headers in Documentation" section. You can browse the list of chapters in the Function Reference to select the chapter that best suits the task you are trying to accomplish. Or, if you happen to know the name of a function that may be in the same scope as the work being done, you can directly press the Quick Ref button to connect to the relevant chapter.
User-Defined Functions
User-defined functions are not necessary in PHP. You can also build useful Web sites using only basic language structures and a large number of built-in functions. However, if you find that the content of your program code is getting longer and longer, and it is becoming more and more difficult to understand and manage, it means that you should think about converting some of your program code into functions.
What is a function?
A function is a way of writing a program that wraps a block of program code and gives it a name. This makes it easier to use the block of program code in the future with only one line of program code. If when writing a program, the program code block is used in many places, the function is the most effective way, but even if it is only used once, the creation and writing of the function will help the program structure, because Can make your program code more readable.
Function definition syntax
A function can be defined in the following form:
function function-name($argument1, $argument2,..)
{
statement1;
statement2;
…
}
The function definition has four parts:
The dedicated word "function"
The name given to the function
The parameter list of the function ($ symbol variables separated by commas)
The function body (large A series of narrative statements in parentheses)
Like variable names, function names must also consist of English letters, numbers and underscores (_), and it cannot start with a number. Unlike variable names, function names are converted to lowercase before storage, so function names can be considered case-insensitive.
What happens when a defined function is called is briefly described as follows:
1. PHP will look for the function by name (if the function has not been defined, an error message will be displayed).
2. PHP replaces the variables (or "formal parameters") in the parameter list in the function definition with the values of the parameters (or "actual parameters").
3. Execute the narrative statement of the function body. If execution reaches the "return" statement in the statement, the function stops execution and returns the specified value. Otherwise, the function will be executed until the last step and no value will be returned.
Please be careful, experienced programmers may notice that the previous description implies call-by-value, not call-by-reference. In the last section of this chapter, we will explain their differences and demonstrate how to call by reference.
Example of function definition
To give a fictitious example, please imagine the following program code, which is designed to help us decide how many bottled drinks to buy (perhaps in the future, supermarkets and old products will already be using it) Destroy wireless web browser to view comparison purchase prices).
$liters_1 = 1.0;
$price_1 = 1.59;
$liters_2 = 1.5;
$price_2 = 2.09;
$per_liter_1 = $price_1 / $liters_1;
$per_liter_2 = $price_2 / $liters_2;
if($per_literl<$per_liter2)
print(“The first deal is better! < BR >”);
else
print(“The second deal is better! < BR >”) ;
Because this type of comparison can be seen everywhere in our web page programming code, we would like to make it a reusable function. One way to do this is to rewrite the example:
function better_deal ($amount_1,$price_1,
$amount_2,$price_2)
{
$per_amount_1 = $price_1/$amount_1;
$per_amount_2 = $price_2/$amount_2;
return($per_amount_1<$per_amount_2);
}
$liters_1 = 1.0;
$price_1 = 1.59;
$liters_2 = 1.5;
$price_2 = 2 .09;
if(better_deal($liters_1,$price_1,
$liters_2,$price_2))
print(“The first deal is better!< BR >”);
else
price(“The second deal is better!< BR >”); The
better_deal function extracts the three lines of program code that perform arithmetic operations and comparisons in the previous program code. It takes four numbers as parameters and returns a Boolean operation. The value of the formula. Like any other Boolean value, it can be embedded in the test portion of an if statement. Although this function is longer than the original program code, rewriting it this way has two advantages: you can use this function in multiple other places in the program (saving the number of lines of the entire program). If you decide to change the calculation method, you only need to Just modify one place.
There is another alternative. If the price comparison is to print out which deal is more cost-effective, you can directly put the output display narrative sentence into the function, as shown below:
function print_better_deal($amount_1,$price_1,
$amount_2,$price_2)
{
$per_amount_1 = $price_1 / $amount_1;
$per_amount_2 = $price_2 / $amount_2;
if($per_amout_1<$per_amount_2)
print("The first The second deal is better! ;
$liters_2 = 1.5;
$price_2 = 2,09;
print_better_deal($liters_1,$price_1,
$liters_2,$price_2);
The first function uses the return statement to transfer a Boolean result , and then the result is used in a test in an if statement. The second function has no return statement because it completes its side effect: displaying text in the user's browser. When the last statement of this function
After the statement is executed, PHP then executes the next statement following the function call.
Comparison of formal parameters and actual parameters
In the previous example, the parameters passed to the function are "variables", but this is not necessarily the case. The actual arguments (that is, the arguments in the function call) can be any expression that can be evaluated. In our example, we can pass numbers to the function call instead of variables, as follows:
Print_bettet_deal(1.0,1.59,1.5,2.09);
Also note that there are two actual things in this example The parameter variable has the same name as the formal parameter (such as $price_1) and the actual parameter has a different name from the formal parameter (such as $liters_1 is different from $amount_1). As will be mentioned in the next section, there is no problem with either method. The formal parameter names of the formula exist completely independently outside the function, even if the function calls itself
The above is the content of PHP Learning Guide - Chapter 8 (1). For more related content, please pay attention to PHP Chinese. Network (www.php.cn)