PHP Learning Treasure-Eighth chapter (i)

Source: Internet
Author: User
Tags php language php website types of functions value of pi
Definition and application of function

This chapter highlights

2 using built-in PHP functions

2 Navigating the Online function manual

2 user-defined functions

2 Price Tips: Variable parameters, reference calls, and variable functions


Any programming language has some sort of procedural abstraction (procedural abstraction, which is to name a chunk of code that can be used when writing other code segments). Some script languages lack this ability, and according to our experience, this can make complex server-side code quickly become impossible to manage.


The mechanism that PHP uses to provide this abstraction is function. There are actually two types of functions in PHP, one of which is already built into the language by the PHP developer, and the other is defined by each PHP programmer.


In this chapter, we'll look at how to use the large number of functions that PHP has provided, and then learn how to define your own functions. Fortunately, there is no difference between using a built-in function and a function of your own definition.


Working with functions

The basic syntax for using (or calling) functions is as follows:


Function_name (expression_1, expression_2,..., expression_n)

It is a type that appears with parentheses and a comma-delimited list of input expressions, called function parameters, after the function name. Depending on the definition, the call function can take no parameters, or it can bring in multiple parameters at the same time.


When PHP encounters a function call, it evaluates each parameter calculation first, and then uses those values as input to the function. After a function executes, the callback value (if there is a callback value) is the result of the entire function expression.


The examples listed below are valid calling methods for PHP built-in functions:


SQTR (9)//square root function, the result is "3"

RAND (10,10+10)//callback value between "10" and "20"

Strlen ("This has characters")//Callback value "22"

Approximate value of pi ()//backhaul P


These functions are called with 1,2,1 and 0 parameters, respectively.

return value and accompanying effect

Each function call is a PHP expression (as with other expressions), and there are only two reasons to include a function in the code: To obtain a callback value, or to get a spin-off effect.

The callback value of a function is the value of a function operation. Using this value can be the same as using the evaluation result of any other expression, for example, you can assign it to a variable, as follows:

$my _pi = Pi ();

Alternatively, you can embed it in a complex expression, as follows:


$approx = SPRT ($approx) * sqrt ($approx)


Functions can also be used to implement a variety of collateral effects, including writing data to files, database operations, and displaying content output in a browser window. It is possible to use both callbacks and accompanying actions, for example, we often use a function with an attendant and return the value at the same time to check whether the function is performing properly



The result of a function can be any type, usually using the array type as a function that returns multiple values.


function manual


PHP's architecture is designed to be smart, making it easy for other developers to extend the extension. Its PHP language itself is easy to understand, out of the flexibility, most of the PHP features have a large number of built-in functions. This means that developers are free to add new built-in functions and can contribute to PHP, which is good because it does not change any part of the PHP user's potential to rely on.


Although this book sped many of the built-in functions, the explanation of some of these functions is more detailed than the online manual, but the manuals provided by Http://www.php.net are important reference resources for functional information. In this book, we will pick and choose the topic we want to extend the description, and the PHP manual content is still the most complete reference in every aspect of PHP. While we want to update the book immediately with future versions of PHP, the online description is the latest in the latest features of PHP's new features, including those that are still in the development state. So it's very helpful to have a look at the official PHP website and the different resources available online.


Although the following information is correct at the time of this book (second edition is 2002). However, there may be some details that are outdated, or because the online manual has been updated or re-organized and is no longer applicable.


To search the online manual, go to the Http://www.php.net website and select the "documentaion" Option tab in the Navigation column on the top right, which will go to a link with a variety of formats and information about the people's manuals. What we want to see is that the thread is an annotated user's manual (currently connected to the View online option on the Documentation page), which allows users to post their own annotations to each page. [Please note: The manual annotation system is not a place to post problems!] If you have questions about use, refer to the mailing list (mailing list) section, which is located in the "support" tab of Www.php.net, or see Appendix D to this book for PHP resources. The manual annotation system is a place to explain and comment on your own words after the user understands it, but it is a good way for us to contribute, and it is possible that it will become the official version of the future, which is a good way for us to make a contribution, which is also a great place to point out confusion and possible problems, but here English "to communicate Oh! ]

The majority of the user manual is a function of the test material, where each built-in function has a separate description page. Each page starts with a description of the function name and a single line, followed by a C-style function header declaration (explained in the next section), followed by a slightly longer description, possibly with one or two examples, and then (in the note book) a comment and opinion report from the user.


The header in the manual

For those unfamiliar with the C function header, the first part of the function manual may not be understood. The Keag type is:

Return-type function-name (typle argl,type2 arg2,...) ;

It indicates the expected function callback value type value, function name and expected parameter type, etc.

Here is a basic header description:

String substr (String String,int startl [, int length]);

This means that the function substr returns a string and expects to get a string and two integers as arguments. In fact, the square brackets on both sides of length indicate that this parameter is optional, so when calling substr, you can take a string string and an int integer, or a string string and two int integers.

Unlike in the case of C, the parameter types declared in the header of these manuals are not absolutely necessary. If you call substr with a number as a parameter, there is no error, it is the first argument that PHP converts to a string before it starts executing the function. However, the parameter type does show the original intention of the function creator, and it is best to use the function in accordance with the type indicated in the manual, or to have sufficient knowledge of the related matters of the type conversion, so that the expected results can be guaranteed.

In general, the type names used in the function manuals are one of 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. A viod type function does not return any value at all, and the mixed parameter type means that the parameter can be of any type.

Query function Manual

What is the best way to find information about a function in the manual? It depends largely on your curiosity and the kind of interest you have. The most common questions about functions are:

I'm going to use an X function, and how does it work?

I need to complete a task of Y, can I do this task with a function?

For the first case, the full version of the online manual provides the people with automatic query based on the function name. In the upper-right navigation column, the "search for" text box is the name of the function, and the function's Web page is displayed after the function is found (you can also select other search objects that contain the entire site's mailing list, which is when you don't know the name of the function you want , but a good place to search for the rough typeface of the desired function can be guessed.

In the second case, it is best to use the hierarchical organizational structure of the function reference (Funcrion Reference, one of the PHP manuals), which is divided into 108 chapters. For example, the previously mentioned substr function is in the "string functions" section of the "headers in documentation" section. Readers can browse through the chapter list of the functional references to choose the chapter that best suits the task that you want to complete. Or, if you happen to know the name of a function, the function may be in the same scope as the work done, and you can simply press the Quick ref button to connect to the relevant section.

User-defined Functions

User-defined functions are not necessary in PHP. You can also build useful Web sites using only basic language constructs and a large number of built-in functions. But if you find that your code content is getting longer and more difficult to understand and manage, it means thinking about turning some of your program code into a function.

What is a function?

The function is to write a program that wraps a block of code and gives it a name, which makes it easy to use the code block in a single line of code. A function is the most efficient way to write a program when it is used in multiple places, but even if it is used only once, the creation and writing of the function will help the program structure, because it will make your code more readable.

function definition Syntax

A function can be defined in the following form:

function Function-name ($argument 1, $argument 2,..)

{

Statement1;

Statement2;

...

}

There are four parts of the function definition:

The term dedicated to "function"

Name of the Help function

parameter list of functions (comma-delimited $ symbol variable)

Function Ontology (a series of narrative statements within curly braces)

Like the variable name, the function name must also consist of an English letter, a number, and a bottom line (_), and it cannot begin with a number. Unlike variable names, function names are converted to lowercase before they are stored, so function names can be treated as case-insensitive.

The situation that occurs when a call uses a defined function is summarized as follows:

1. PHP searches for the function by name (an error message is displayed if the function has not been defined).

2. PHP substitutes the value of the parameter (or "actual parameter") for the variable (or "formal parameter") of the parameter list in the function definition.

3. A narrative statement that executes a function ontology. If the "return" statement is executed into the narration, the function stops executing and returns the specified value. Otherwise, the function is executed until the last, and no value is returned.

Be careful, the experienced programmer may notice that the preceding description implies that it is a call by value (Call-by-value) instead of a call (Call-by-reference) by reference. The differences are explained in the last section of this chapter and demonstrate how to make calls by reference.

Example of a function definition

To give a fictitious example, consider the following code, which is designed to help us decide how many bottled drinks to buy (perhaps in the future, the super-old product has already been using a wireless web browser to compare the price of the purchase).

$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 is ubiquitous in our web page code, we want to make it a reusable function. One way to do this is to rewrite it as an 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 code in the previous code for arithmetic operations and comparisons, with four numbers as arguments, and returns the value of a Boolean expression. As with any other Boolean value, it can be embedded in the test part of the IF narrative. Although this function is longer than the original code, this rewrite has two advantages: You can use this function in many other places of the program (saving the total number of program lines), if you decide to change the calculation method, only need to modify a place.

There is also an alternative, if the price comparison is to print out which transaction is more cost-effective, it can directly put the output display narrative sentence into the function, as follows:

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 deal is better!< BR >");

Else

Print ("The second deal is better!< BR >");

}

$liters _1 = 1.0;

$price _1 = 1.59;

$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 route a Boolean result, which is then used in a test that is described. The second function does not have a return statement because it accomplishes its incidental effect: the user's browser is the display text. When the last narrative of this function
After the statement is executed, PHP then executes the next narrative statement after the function call.

Comparison of formal parameters and actual parameters

In the previous example, the arguments passed to the function are "variables", but they are not necessarily handled as such. The actual parameter (the parameter in a function call) can be any expression that evaluates the evaluation. In our example, you can give a function call an incoming number without a variable, as follows:

Print_bettet_deal (1.0,1.59,1.5,2.09);

Also note that in this example there are two instances where the actual parameter variable has the same name as the formal parameter (such as $price_1 and the actual parameter differs from the formal parameter name (for example, $liters_1 and $ amount_1). In the next section, there are two ways to do this, and the formal parameter names of functions are completely independent, even if the function calls itself.

The above is the PHP learning treasure-The eighth chapter (a) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.