PHP Basic Tutorial Five functions

Source: Internet
Author: User
Tags benchmark mathematical functions function calculator


What this section explains

    • The concept of a function

    • Classification of functions

    • The variable problem of the function

    • Argument discussion of function

    • Intrinsic functions

    • Variable functions

    • anonymous functions

    • recursive invocation of functions

Objective


In PHP development, we sometimes use a lot of functions, what is a function, what is the role? The appearance of the function can be said to introduce the concept of encapsulation for the first time, the use of functions can make our code less redundant, and the definition of the function can be on our rapid filtering ideas. Improves code reusability and facilitates modular programming.

The concept of a function

When we are in programming, there is a need for a unified integration of a feature so that it is not written once (less redundant) when it is used elsewhere, and it is only possible to invoke specific code. With out-of-the-box technology, it is difficult to achieve this requirement, and we need to use the knowledge of functions.

Function: A collection of program directives (statements) that perform a function , generally a function that is best accomplished only to reduce the degree of coupling of the code.

Sometimes we call functions a method, and they are both a concept.

Classification of functions

The functions of almost every programming language are divided into two types:

    • Custom functions

    • System functions

Custom functions:
A custom function is a function that we define ourselves according to our own specific requirements, and the functions in the function need to be implemented by ourselves.

Syntax rules for custom functions:

function method Name (parameter list) {The    code that implements a function; return    value (can have no return value, see demand)}

Explain:

    1. function is a keyword that must be written if you want to define a

    2. The method name is your own definition, the name you can play, but generally we should make meaningful names, such as the function to achieve what function of the abbreviation.

    3. Formal parameter list, when we call the function, sometimes we need to pass to the function some parameters (that is, variables), in the function, the parameter list is to accept the arguments passed when we call, of course there can be more than one.

    4. In PHP, the function body is enclosed in curly braces, which write our code.

    5. Return is the meaning of returning, when we call the function, sometimes we need the function to return a result, such as function is to calculate the sum of two numbers, when the function through the addition operation, we can write a return to return the results of the calculation, Of course there is no return value to see what the function's specific function is, and need not return the result.

Naming rules for function names:
The function name is the same as the other identifier naming rules in PHP. Valid function names begin with a letter or underscore, followed by letters, numbers, or underscores.
We write the function is the general naming convention is the camel-named method, that is, the first letter of the second word capitalized.

Example:

<?php$a = n; $b = 6;function sum ($num 1, $num 2) {//These two parameters are the parameters that are passed when we call    $res = $num 1 + $num 2;    return $res; Computes the number of two and returns it to the caller. } $sum = SUM ($a, $b); Call the function, here we will pass the past two parameters, and return the results with $sum receive. Echo $sum;

System functions:

System function is also a function, is the system has been encapsulated functions, system functions have many, different functions have different functions, we can choose different functions according to their own needs.

In the Help document we can query the mathematical functions we use frequently:

    1. abs-Absolute Value

    2. Ceil-into one method to take the whole

    3. decbin-Decimal conversion to Binary

    4. dechex-decimal conversion to hexadecimal

    5. decoct-Decimal conversion to octal

    6. max-Find the maximum value

    7. min-Find the Minimum value

    8. pow-exponential expression

    9. Rand-produces a random integer

    10. Round-rounding of floating-point numbers

    11. sqrt-Square Root

The Var_dump () output type that we sometimes use is the system function.

The help document can be viewed when the system function is used.

The variable problem of the function

Global variables and local variables

Local variables:

In the function we are working with the data, we may define variables that are defined in the function as local variables, Local: As the name implies, is the variable used in the function.

<?php$a = n; $b = 6;function sum ($num 1, $num 2) {    $res = $num 1 + $num 2;//defines a variable to store two numbers of sums.    return $res;} $sum = SUM ($a, $b); Echo $res; Attempt to output outside of the function. Echo $sum; Results..... notice:undefined variable:res in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\yusuanfu.php on line 1418

You can see an error when trying to use a variable inside a function outside of a function.

Global variables:

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

b, this variable defined outside the function is called a global variable. So can global variables be used within functions again?


<?php$a = n; $b = 6;function sum ($num 1, $num 2) {    $res = $num 1 + $num 2;    echo $a;//output variables outside the function within the function.    return $res;} $sum = SUM ($a, $b); Echo $sum; Results..... notice:undefined variable:a in D:\mywamp\Apache24\htdocs\zendstudio\yunsuanfu\yusuanfu.php on line 10

You can see that there is an error when using a global variable outside the function within a function.

Global variables are called global, so how do you use them inside a function? The answer is simple, just declare it with the keyword in the function.

<?php$a = n; $b = 6;function sum ($num 1, $num 2) {    $res = $num 1 + $num 2;    Global $a;//variables outside the function are output within the function.    echo $a;    return $res; } $sum = SUM ($a, $b); Results..... 12

The use of global as the keyword in the function declares that you need to use the globally variable $ A, where you have to say the changes in memory of the function's call.

The procedure for calling a function is roughly a diagram:

Our code runs in the stack (that is, in memory). In the stack through a row of execution code, to parse, at run time there is a storage area of our data, called the data area. When a variable is defined, a data area is generated in the data area, storing its own defined variables.

When the code executes to the calling function, the system re-opens a stack in the stack and executes the function in the new stack (a new stack is opened for each function), and when the object is created in the function, an area is redefined in the data area to hold the variables in the function. This is why you cannot use variables inside a function outside of a function. Two of them are two different regions.

But when we declare global, the system does not create a variable in the function's own data area, but instead goes to the data area outside the function and tries to find a variable defined with global. But when the external data area does not have a variable that we define with global, it automatically defines a variable in the outer data area, making it a global variable.

<?php$b = 6;function sum ($num 1) {    global $a;//define an externally-not variable within a function by using global.    $a = 23;//Assign values within functions. } $sum = SUM ($b); Echo $a; Directly use variables within the function. ..... Results..... 23

$ A above is not defined externally

Argument discussion of function

We often pass arguments when we call a function, and we define parameters to accept them on the function. Call function simultaneous parameter is called the actual parameter (argument), and the function accepts the parameter is called the formal parameter (formal argument), it two is not affected, the definition of the same name is also possible, but must correspond, cannot appear to call simultaneous past two parameters, receive a parameter.

The parameter of the function is allowed to have a default value, that is, when we do not pass the value of the past, it uses the default value, but when we pass past the value of the time, we use to pass the value of the past.

Use the default:

<?php$a = 3; $b = 6;function sum ($a, $b, $oper = ' + ') {//Parameters and argument names can be the same.    if ($oper = = ' + ') {         echo $a + $b;//Use the default plus    }else if ($oper = = '-') {        echo $a-$b;    }} $sum = SUM ($a, $b); Only two parameters are passed in, and the operator uses the default condition. ..... Results..... 9

You can see that it has no error, and $oper uses the default value +;

Used to pass through:

<?php$a = 3; $b = 6;function sum ($a, $b, $oper = ' + ') {//Parameters and argument names can be the same.    if ($oper = = ' + ') {         echo $a + $b;     } else if ($oper = = '-') {        echo $a-$b;//Use a pass-through    }} $sum = SUM ($a, $b, '-');//pass over three parameters.

Value passing and reference passing of parameters

In a function call, there are two ways to pass a parameter:

    • Value passing

    • Reference delivery

Value passing

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

<?php$a = 12;function SetA ($a) {     $a = $a * 12;//The value of $ A is multiplied by 12;}seta ($a);//Call function echo $a; Results..... 12

This is passed as a value, and by default, the function argument is passed by value (so that the value of the parameter is not changed outside of the function even if it is changed internally). If you want to allow a function to modify its parameter values, you must pass the arguments by reference.

Reference parameters

Sometimes we want the value that we pass in, in the case of no return, to modify it directly, it is necessary to use the reference pass.

<?php$a = 12;function SetA (& $a) {  //Just add a fetch address symbol in front.    $a = $a * 12;//The value of $ A is multiplied by a number of,/    /function has no return value}seta ($a);//Call function echo $a; Results..... 144

In the above code just add a fetch address character & in the function, and learn C language know, in C language use & Direct address delivery. This means that the data in the function will point to the outside variable.

Intrinsic functions

Intrinsic functions: Functions can be declared inside the function for internal use, called intrinsic functions
, such as a programmer to prevent others from invoking, you can use intrinsic functions.

<?php$a = n; $b = 6;function Calculator ($a, $b) {function    sum ($a, $b) {//define a function inside the function,        return $a + $b;    }    function subtract ($a, $b) {        return $a-$b;    }    return sum ($a, $b); Call your own defined function and pass through the two values passed in. }echo calculator ($a, $b); The function is called to output the returned result directly. ..... Results..... 18

In fact, internal functions can also be used outside the function, like the above code, if we do not execute calcuator, we call the internal function sum (), will be an error. But if we do calculator, we can also use intrinsic functions.

<?php$a = n; $b = 6;function Calculator ($a, $b) {function    sum ($a, $b) {//define a function inside the function,        return $a + $b;    }    function Subtract ($a, $b) {        return $a-$b;    }} Calculator ($a, $b); Call function echo sum ($a, $b); This can be called after the above call, or it will go wrong. ..... Results..... 18

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

Variable functions

mutable functions: PHP supports the concept of mutable functions. This means that if a variable name has parentheses after it, 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 to implement some purposes, including callback functions, function tables, and so on.

Look at the code to understand clearly what a mutable function is.

<?php$a = n; $b = 6;function Add ($a, $b) {    $res = $a + $b;    echo $res;} $fun _name = ' add ';//defines a variable whose name is the function name of the function. $fun _name ($a, $b); Think of a variable as a function name ..... Results..... 18

We will use this method in the callback function.
Case LIST:

<?php$a = 6; $b = 6;function getval ($a, $b, $fun _name) {//The third parameter is the name of a function.    return $fun _name ($a, $b);//If a variable name has parentheses after it, look for a function with the same name as the value of the variable, and try to execute it. }function sum ($a, $b) {//This function is actually called in Getval.    return $a + $b;} Echo getval ($a, $b, ' sum '); Results..... 12

Pass the name of a function as a variable on top of it.

anonymous functions

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

<?php$a = 6; $b = 16;function getval ($a, $b, $fun _name) {     return $fun _name ($a, $b);} Echo getval ($a, $b, function ($a, $b) {//The temporary definition of an anonymous function at the time of delivery, no name, only the keyword function.    return $a + $b;}); ..... Results..... 22

callback function

The code above is actually a callback function. The anonymous function is called as a callback function.

The simple understanding of a callback function is that you call a function, and the function (a) invokes another function (b) that you implement, so the other function (b) is called a callback function, so, in general, you just don't call it directly.

recursive invocation of functions

Recursive straightforward is to call themselves, such as functions themselves call themselves, recursion is an algorithm, its professional statement is:

Recursion by transforming a large and complex problem layer into a small problem similar to the original problem, the recursive strategy can describe the repeated computations required by the process of solving the problems by a small number of programs, which greatly reduces the code volume of the program.

We are here to simply discuss, do not do too much in-depth.

Example:

<?phpfunction ABC ($n) {    if ($n > 2) {        ABC (--$n);//Make Yourself call yourself.    }    The value of Echo ' $n is '. $n. ' <br> ';} ABC (4); Results..... 2 2 3

See the results may not be reflected in a moment. But if the drawing is good to understand.

The recursive function needs to satisfy several conditions:
-benchmark scenario. There must always be some benchmark conditions, which can be solved without recursion
-Keep pushing. For cases where recursion is required, each recursive invocation must push the state toward a baseline situation

Summarize

The above explanation is basically the basic application of the function, want to be familiar with the application of the function, only use more practice, think more. At the same time, do not know if there is no discovery, this section of the function is written in a file, but sometimes we write the function is in another file, then we can not use another file directly, the above all the functions can not be used, as a PHP programmer, you have to know, there must be a way to solve this problem, um , can solve, include and require.

The above is the PHP Basic tutorial Five of the contents of the function, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.