PHP basic tutorial 5 functions

Source: Internet
Author: User
Tags decimal to binary function calculator
This section describes the concepts of functions. classification of functions. variable issues of functions. parameters of functions. discussion of internal functions. variable functions. recursive calls of anonymous functions.


Content described in this section
  • Function concept

  • Function category

  • Variable issues of functions

  • Function parameters

  • Internal functions

  • Variable functions

  • Anonymous functions

  • Recursive call of functions

Preface


In PHP development, we sometimes use a large number of functions. What are functions and what are their functions? The appearance of functions can be said to have introduced the concept of encapsulation for the first time. the use of functions can make our code less redundant, and the definition of functions can be quickly filtered out. Improves code reusability and facilitates modular programming.

Function concept

When we have such a requirement in programming, we need to integrate a function in a unified manner so that we do not have to write this function once (to reduce redundancy) when using it elsewhere ), you only need to call specific code. With the existing technology, it is difficult for us to achieve this requirement. in this case, we need to use the function knowledge.

Function: a set of program commands (statements) to complete a function,Generally, it is better for a function to complete only one function to reduce the coupling of code.

Sometimes we call functions as methods. They are two concepts.

Function category

Functions in almost every programming language are divided into two types:

  • Custom functions

  • System functions

Custom functions:
User-defined functions are defined by ourselves based on our specific needs. the functions in the functions need to be implemented by ourselves.

Syntax rules for custom functions:

Function method name (parameter list) {code that implements a certain function; return value (no return value is allowed, as required )}

Explanation:

  1. Function is a keyword. to define a function, you must write the function.

  2. The method name is defined by yourself. you can use this name at will, but we should generally give it a meaningful name, for example, the abbreviation of the function to be implemented.

  3. Parameter list. when we call a function, we sometimes need to pass some parameters (that is, variables) to the function for operations, this parameter list is the parameter that is passed when we call it. Of course there can be multiple parameters.

  4. In PHP, the function body needs to be enclosed in braces to write our code.

  5. Return is the meaning of return. when we call a function, sometimes the function needs to return a result to us. for example, the function is used to calculate the sum of two numbers. at this time, after the function passes the addition operation, we can write "return" to return the calculated result. of course, whether or not to return the result depends on the specific function of the function.

Naming rules for function names:
The name of the function is the same as that of other identifiers in PHP. A valid function name must start with a letter or underline followed by a letter, number, or underline.
When writing a function, the general naming rule is the hump naming method, that is, the first letter of the second word is capitalized.

Example:

 

System functions:

A system function is also a type of function. it is a function that has been encapsulated by the system. There are many system functions. different functions have different functions. we can select different functions as needed.

In the help document, we can query our frequently used mathematical functions:

  1. Abs-absolute value

  2. Ceil-integer in one method

  3. Decbin-decimal to binary

  4. Dechex-decimal to hexadecimal

  5. Decoct-decimal to octal

  6. Max-find the maximum value

  7. Min-find the minimum value

  8. Pow-exponential expression

  9. Rand-generate a random integer

  10. Round-rounding floating point numbers

  11. Sqrt-square root

The var_dump () output type that we sometimes use is a system function.

You can view the help documentation when using system functions.

Variable issues of functionsGlobal and local variables

Local variables:

In a function, we may define some variables in processing data. these variables defined in the function are called local variables. local variables are the variables used in the function, as the name suggests.

  

You can see that an error is reported when you try to use the variable in the function outside the function.

Global variables:

In the code above, we can see that, outside the function, we define two variables,

B. The variables defined outside the function are called global variables. So can Global variables be used in the function?


   

You can see that an error is prompted when you use a global variable outside the function.

Global variables are called global variables. how can we use them in functions? The answer is simple. just declare it with keywords in the function.

    

When using the global keyword to declare a function, you need to use the global variable $.Changes in the memory of function calls.

The calling process of a function is shown in the following figure:

Our code runs in the stack (that is, the memory. In the stack, a line of code is executed to parse the code. during the operation, there is a region that stores our data, called the Data Zone. When a variable is defined, a data zone is generated in the data zone to store the defined variables.

When the code is executed to call a function, the system will re-open a stack zone in the stack, and execute functions in the new stack (each time a function is executed, a new stack is opened up). When an object is created in a function, A region is redefined in the data zone to store the variables in the function. This is why function variables cannot be used outside the function. The two are two different regions.

However, when we declare global, the system will not create a variable in the function's own data zone, but will go to the external data zone of the function and try to find the variables defined by global. However, when the external data zone does not have a global variable, a variable is automatically defined in the external data zone to make it a global variable.

     

The above $ a is not defined externally

Function parameters

When we call a function, we often pass over parameters. in the function, we also define parameters for acceptance. The parameter passed when a function is calledActual parameters(Real parameter), and the parameter accepted by the function is calledFormat parametersThe two parameters are unaffected. They can also be defined with the same name, but must correspond to each other. The two parameters must not be passed during the call.

Function parameters allow default values, that is, when we do not pass the past value, it uses the default value, but when we pass the past value, we use the passed value.

Use the default:

      

It can be seen that no error is reported, and $ Pipeline uses the default value +;

Use the following:

       Parameter value transfer and reference transfer

In function calls, there are two ways to pass parameters:

  • Value Transfer

  • Reference transfer

Value Transfer

When we call a function, pass the parameter, and modify it in the function, and use it again outside the function, or the value before modification, you can see the code:

        

This method is passed as a value. by default, a function parameter is passed through a value (so it does not change the value outside the function even if the parameter value is changed inside the function ). If you want to allow a function to modify its parameter values, you must pass parameters through reference.

Reference parameters

Sometimes we want to directly modify the value we pass in without returning it. This requires reference transfer.

         

In the above code, I only added an address get operator to the function. anyone who has learned the C language knows how to use it in the C language and directly transfer the address. This indicates that the data in the function will point to the external variable.
For example, a programmer can use internal functions to prevent calls by others.

          

In fact, internal functions can also be used outside the function, just like the above code. if we do not execute calcuator, we will call the internal function sum () and an error will be reported. However, if calculator is executed, we can also use internal functions.

           

When calcuator is called, it can be understood that there are two functions in the memory, and then the functions in the function are called, so there will be no error.

Variable functions

Variable functions: PHP supports the concept of variable functions. This means that if a variable name has parentheses, PHP will look for a function with the same name as the value of the variable and try to execute it. Variable functions can be used for some purposes, including callback functions and function tables.

You can clearly understand what a variable function is.

            

This method is used in the callback function.
Case column:

             

Use the name of a function as a variable for transmission.

Anonymous functions

Anonymous function: an anonymous function, also called a closure function, allows temporary creation of a function without a specified name. The value that is most often used as the callback function parameter. Of course, there are other applications. a simple understanding is that an anonymous function is a function without a name.

              Callback function

The above code is actually a callback function. Anonymous functions are called as callback functions.

A simple understanding of A callback function is that you call A function, and this function (A) calls another function (B) implemented by you ), so this other function (B) is called a callback function. Generally, you just don't call it directly.

Recursive call of functions

Recursion refers to self-calling itself. for example, if a function calls itself, recursion is an algorithm. its professional saying is:

Recursion solves a large and complex problem by converting it into a small problem similar to the original problem, the recursive strategy can describe the repeated computing required in the problem-solving process with only a small number of programs, greatly reducing the amount of code in the program.

Here we will just give a brief discussion and do not go into depth too much.

Example:

               2) {abc (-- $ n); // call yourself. } Echo '$ n is'. $ n .'
';} Abc (4); ...... result ...... 2 2 3

The result may not be reflected at the moment. However, if you draw a picture, you can understand it.
-Continuous promotion. For situations that require recursive resolution, each recursive call must push the condition toward a baseline.

Summary

The above explanation is basically the basic application of functions. if you want to be familiar with the application of functions, you only need to practice more and think more. At the same time, I don't know if I have found that all the functions in this section are written in one file. However, sometimes the function we write is in another file, so that we cannot directly use another file, none of the above functions can be used. as a PHP programmer, you must know that there must be a way to solve this problem. well, it can indeed solve, include and require.

The above is the function content of PHP basic tutorial 5. For more information, please follow the PHP Chinese network (www.php1.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.