PHP learning note function

Posted by iambradn on Tue, 25 Jan 2022 13:59:39 +0100

The concept of function in PHP

Function is a form of organizing some statements with certain functions. The purpose of defining function is to divide the program into functional blocks to facilitate the use, management, reading and debugging of the program. There are two kinds of functions: one is a function written by others or provided within the system. As long as you know what this function is for, you can use it by yourself, regardless of how it is implemented; The other function is self-defined and used to realize its own unique requirements.

For example, if you get the day of the week, you can package it into a function and call it when you want to use it.

<?php
    function get_week($dates){
        $weekarray=array('day','one','two','three','four','five','six');
        echo $dates.' It's a week'.$weekarray[date('w',strtotime($dates))];
    }
    get_week('2008-08-08'); #Call function

Function definition

function Function name (Parameter 1, Parameter 2, ..., parameter n){
    Function body;
    return Return value;
}

The syntax format of the function is described as follows:

  • The first line of each function is the function header, which is composed of the keyword function, function name and parameter list of the declared function, each of which completes a specific function.
  • Each custom function must be declared using the function keyword.
  • The function name can represent the whole function, and the function can be named any name, as long as the naming rules of variable names are followed. Each function has a unique name, but it should be noted that function overloading cannot be used in PHP, so functions with duplicate names cannot be defined, including functions with the same name as system functions.
  • When declaring a function, the parentheses "()" after the function name are also required. The parentheses contain a list of acceptable parameters. The parameters are the declared variables, and then the variables can be passed to the function when calling the function. The parameter list can be empty or have one or more parameters separated by commas.
  • The function body is located behind the function header and enclosed in curly braces. The actual work is done in the function body. After the function is called, first execute the first statement in the function body, end after executing the return statement or the outermost curly bracket, and return to the calling program. Any valid PHP code can be used in the function body, and even the definitions of other functions or classes can be declared in the function body.
  • Use the keyword return to return a value or expression from a function. When the program executes the return statement, the expression will be evaluated, and then return to the place where the function is called to continue execution.

You can declare a function without a parameter list, or you can declare a function without a return value.

Function call

Whether it is a custom function or a system function, if the function is not called, it will not be executed. Just use the function name and parameter list to call where you need to use the function. After the function is called, it starts to execute the code in the function body. After execution, it returns to the called position and continues to execute downward.

After the function is called, it starts to execute the code in the function body. After execution, it returns to the called position and continues to execute downward. Therefore, when calling a function, the function name can summarize the following three functions.

  • The function can be called through the function name and the code of the function body can be run. The function body will be executed several times after being called several times.
  • If the function has a parameter list, you can also change the execution behavior of the internal code of the function by passing the corresponding value to the parameter in the parentheses after the function name and using the parameter in the function body.
  • If the function has a return value, the value after return will be returned to the location of the calling function when the function is completed. In this way, the function name can be used as the return value of the function.

Tip: as long as the declared function is visible in the script, it can be called anywhere in the script by the function name. In PHP, it can be called after the declaration of the function, it can also be called before the declaration of the function, and the function can also be called in the function.

Simple example:

<?php
    function add($num1,$num2){
        $a = $num1 + $num2;
        return $a;
    }
    $sum = add(11,77); #call
    echo '$sum = '.$sum.'<br>';

Parameters of function

Formal parameter, argument

The parameter list consists of 0, one or more parameters. Each parameter is an expression separated by commas. For parameterized functions, there is a data transfer relationship between the PHP script and the called function. When defining a function, the expression in parentheses after the function name is called formal parameter (hereinafter referred to as "formal parameter"), and the expression in parentheses after the called function name is called actual parameter (hereinafter referred to as "actual parameter"), and the actual parameter and formal parameter need to pass data in sequence.

<?php
    function add($a, $b){ # $a, $b formal parameters
        echo $a.' + '.$b.' = '.($a+$b).'<br>';
    }
    add(11, 32); # 11,32 arguments

Starting with PHP 8.0.0, the function parameter list can contain a trailing comma, which will be ignored.

Pass parameters by reference

By default, function parameters are passed by value (so even if you change the value of the parameter inside the function, it does not change the value outside the function). If you want to allow a function to modify its parameter values, you must pass parameters by reference.

<?php
    function add(&$a, &$b)
    {
        $a = 2;
        $b = 1;
    }
    $a = 1;
    $b = 2;
    add($a, $b);
    var_dump($a, $b);

The value of the default parameter

The default value must be a constant expression, not a variable, class member, or function call.

<?php
    function add($a = 1, $b = 1)
    {
        echo $a.' + '.$b.' = '.($a+$b).'<br>';
    }
    add();
	add(2);

Note: parameters passed to reference can also have default values.

Variable number of parameter lists

PHP supports a variable number of parameter lists in user-defined functions. By Syntax implementation.

be careful: You can also use the following functions to get variable parameters func_num_args(), func_get_arg() and func_get_args(),This method is not recommended, please use ... Instead.

contain... Will be converted to an array of specified parameter variables, as shown in the following example:

<?php
    function add(...$value) {
        $a = 0;
        foreach ($value as $n) {
            $a += $n;
        }
        echo $a.'<br>';
    }
    echo add(1, 2, 3, 4, 5, 6, 7);

You can also use Syntax to pass array

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2]).'<br>';

You can Specify normal position parameters before. In this case, only tail parameters that do not match the position parameters will be added to In the generated array.

You can also Add a type declaration before the tag. If this is the case, then All parameters captured must be objects of the prompt class.

Named parameters

PHP 8.0.0 introduced named parameters as extensions to existing positional parameters. Named parameters allow parameters to be passed to functions based on parameter names rather than parameter positions. This makes the meaning of parameters self-contained, independent of order, and allows arbitrary skipping of default values.

Named parameters are passed by prefixing the parameter name with a colon. Reserved keywords are allowed as parameter names. The parameter name must be an identifier and cannot be specified dynamically.

<?php
    function add(a:$a, b:$b)
    {
        echo $a.' + '.$b.' = '.($a+$b).'<br>';
    }
    $a = 1;
    $b = 2;
	add(b:$a,a:$b);

PHP declaration parameter type

stay PHP The parameter type declaration of the function has been introduced in 5. If the given value is not a legal parameter type, a Fatal error will appear in PHP 5 and a TypeError exception will be thrown in PHP 7.

The declarable types of parameters are added in PHP 7, as shown in the table.

typeexplainPHP version
class/interface nameThe parameter must be an instance of the specified class or interfacePHP 5.0.0
ArrayParameter is array typePHP 5.1.0
CallableParameter is a valid callback typePHP 5.4.0
BoolThe parameter is BooleanPHP 7.0.0
FloatThe parameter is floating pointPHP 7.0.0
IntParameter is integerPHP 7.0.0
StringThe parameter is a stringPHP 7.0.0

Type conversion

By default, when the parameter passed is not the parameter type specified by the function, PHP will try to convert the passed parameter to the specified parameter type.

Strict mode

In PHP 7, you can use declare(strict_types=1) to set strict mode, so that it can be executed correctly only when the passed parameters are consistent with the expected parameter types of the function, otherwise an error will be thrown. There is only one exception, that is, when the function expects a floating-point data and provides an integer, the function can also be called normally.

Return value of function

The value is returned by using an optional return statement. You can return any type including arrays and objects. The return statement immediately aborts the function and returns control to the line of code that calls the function.

If return is omitted, the return value is null.

Return you can only return one parameter at a time. If you want to return multiple parameters, you need to use an array:

<?php
    function get_numbers()
    {
        return array (0, 1, 2);
    }
    list ($zero, $one, $two) = get_numbers();

To return a reference from a function, the reference operator must be used when the function declares and assigns the return value to a variable &:

<?php
function  &test() {
     static  $a =0; //Declare a static variable
     $a ++;
     return  $a ;
}

$a =&test();
echo $a.'<br>';// 1

$a = 500;
echo test().'<br>'; //501
?>

In addition, a new function has been added in PHP7 - declaring return value types. Similar to declaring parameter types, in non strict mode, PHP will try to convert the return value type to the declared type. If the conversion fails, a Fatal error will be reported. However, in strict mode, the return value of the function must be consistent with the declared return type (no type conversion will be attempted on the return value). If it is inconsistent, a Fatal error will also be reported.

<?php
    function add($a, $b):float{
        return $a + $b;
    }
    var_dump(add(11, 77));
?>

Strict mode:

<?php
    declare(strict_types=1);
    function add($a, $b):int{
        return $a + $b;
    }
    var_dump(add(11, 77));
	var_dump(add(11, 77.8)); //abnormal
?>

Anonymous function

Understanding anonymous functions

Anonymous functions are functions without function names, also known as closures, which are in PHP5 A new feature is added in 3. The value most often used as the callable parameter of the callback function. Of course, there are other applications.

Anonymous functions are currently implemented through the Closure class.

Anonymous functions can be used as values of variables:

<?php
    $a = function (){
        return 'Anonymous function';
    };
    echo $a();

PHP will automatically convert this expression into an object instance of the built-in class closure. The method of assigning a closure object to a variable is the same as that of ordinary variables, and a semicolon should be added at the end;

Anonymous functions are usually used as callbacks to functions or methods. Anonymous functions are used in many PHP built-in functions, such as array_map and preg_replace_callback.

<?php
    $arr    = [1,2,3];
    $result = array_map(function ($num) {
        return $num*$num;
    }, $arr);
    echo '<pre>';
    print_r($result);
?>

use keyword

Using the use keyword, the closure function can inherit variables from the parent scope, but from php7 Starting from 1, inheritance of predefined variables and $this is not supported.

<?php
    $a = 1;
    $b = 2;
    $test = function() use ($a) {
        echo '$a = '.$a.'<br>';
        echo '$b = '.($b??'No definition').'<br>';
    };
    $test();
?>

It should be noted that although anonymous functions can inherit variables in the parent scope, modifying the value of variables in anonymous functions will not affect variables in the parent scope. The example code is as follows:

<?php
    $a = 1;
    $b = 2;
    $test = function() use ($a) {
    	$a = 2;
        echo 'Anonymous function $a = '.$a.'<br>';
    };
    $test();
    echo 'overall situation $a = '.$a.'<br>';
?>

If you want to modify the variables inherited by anonymous functions as well as the variables in its parent scope, you need to add the & symbol in front of the variable name, which is similar to reference passing in functions.

Automatically bind $this

When declared in the context of a class, the current class is automatically bound to it, making $this available in the scope of the function.

<?php
    class Test
    {
        public function testing()
        {
            return function() {
                var_dump($this);
            };
        }
    }
    $object = new Test;
    $function = $object->testing();
    $function();
    //Result object(Test)#1 (0) {}
?>

If you do not need the automatic binding of the current class, you can use static anonymous functions instead.

Static anonymous function

Anonymous functions are allowed to be defined statically. This prevents the current class from automatically binding to them, and objects may not be bound to them at run time.

<?php
    class Foo
    {
        function __construct()
        {
            $func = static function() {
                var_dump($this);
            };
            $func();
        }
    };
    new Foo();// Result: an error is reported
?>

PHP variable function

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

It should be noted that variable functions cannot be directly used for echo, print, unset(), isset(), empty(), include, require, and similar language structures. You need to use self wrapped functions to use these structures as variable functions.

<?php
	function a(){
        echo 'a()';
    }
    function b(){
        echo 'b()';
    }
	$c='a';
	$c();
	$c='b';
	$c();
?>

It can be seen that the $c() function is also called, and different functions are called with the change of variable value.

PHP callback function

The so-called callback function means that when calling a function, it does not pass a standard variable as a parameter, but another function as a parameter to the called function. If a parameter of type "callback" appears in the format description of a function, the function is a callback function.

Declare your own callback function with variable function:

<?php
    function test($func){
        for($i=1;$i<100;$i++){
            if($func($i))
                continue;
            echo $i.'<br>';
        }
    }
    function two($i){
        return $i%2!=0;
    }
    function three($i){
        return $i%3!=0;
    }
    test('two'); //Divide by 2 within 100
    test('three'); //Divide by 3 within 100
?>

call_user_func_array() function custom callback function

The function has two parameters: the first parameter needs to be a string indicating the name of the function to be called because the pseudo type callback is used; The second parameter is an array type parameter, which represents the parameter list and is passed to the function to be called in order.

<?php
    function test($func){
        for($i=1;$i<100;$i++){
            if(call_user_func_array($func,[$i]))
                continue;
            echo $i.'<br>';
        }
    }
    function two($i){
        return $i%2!=0;
    }
    function three($i){
        return $i%3!=0;
    }
    test('two'); //Divide by 2 within 100
    test('three'); //Divide by 3 within 100
?>

All use call_ user_ func_ The custom callback function implemented by the array() function, or all callback functions provided to us in the PHP system, can use array type values in the first parameter, and two elements must be used in the array:

  • If you call a member method in a class, you need to specify in this array parameter that the first element is the class name string and the second element is the static method name string in the class.
  • If you call the member method name in the object, the first element in the array is the reference of the object, and the second element is the member method name string in the object.

PHP also provides call_user_func()

And call_ user_ func_ The difference between the array () function is: call_user_func_array() receives the parameters of the callback function in the form of an array, and call_user_func() receives callback function parameters with specific parameters.

<?php
    function test($func, $a, $b) {
        return call_user_func($func, $a, $b);
    }
    function add($m,$n){
        return $m+$n;
    }
	function sub($m,$n){
        return $m-$n;
    }
    echo test('add', 1, 2).'<br>';
    echo test('sub', 2, 1).'<br>';
?>

PHP recursive function

Recursive functions are self calling functions, that is, functions call themselves directly or indirectly within the function body. Usually, a judgment condition is attached to the function body to judge whether the recursive call needs to continue. When the condition is met, the recursive call of the function will be terminated.

<?php
    function test($n) {
        echo $n."&nbsp;&nbsp;";
        if($n>0)
            test($n-1);
        else
            echo '<-->';

        echo $n."&nbsp;&nbsp;";
    }
    test(10);
?>

The implementation results are as follows, and the causes of the second half are analyzed.

10  9  8  7  6  5  4  3  2  1  0  <-->0  1  2  3  4  5  6  7  8  9  10  

Calculate the Fibonacci sequence:

1,1,2,3,5,8,13,21,34,...

The implementation code is as follows:

<?php
    function test($num){
        //
        if($num == 1 || $num == 2){
            return 1;
        }else{
            return test($num - 1) + test($num - 2);
        }
    }
    echo 'The 10th place in the sequence is:'.test(10);
?>

The operation results are as follows:

The 10th place in the sequence is 55

Internal (built-in) functions

PHP has many standard functions and structures. There are also functions that need to be compiled with specific PHP extensions, or you will get a fatal "undefined function" error when using them. For example, to use imagecreatetruecolor() in the image function, you need to add GD support when compiling PHP. Alternatively, use MySQLi_ For the connect () function, you need to add MySQL support when compiling PHP. There are many core functions already included in each version of PHP, such as string and variable functions. Call phpinfo() or get_loaded_extensions() can tell which extension libraries PHP has loaded. It should also be noted that many extension libraries are valid by default.

Arrow function

The basic syntax of the arrow function is

fn (argument_list) => expr
  • Arrow function is a new syntax in PHP 7.4. It is a more concise way to write anonymous functions.

  • Both anonymous functions and arrow functions are implementations of the Closure class.

  • The arrow function supports the same function as the anonymous function, except that the variables in its parent scope are always automatic. When a variable used in an expression is defined in the parent scope, it is implicitly captured by value.

    <?php
    	$b = 1;
    	$fn1 = fn($a) => $a + $b;
    	// Equivalent to using $y by value:
    	$fn2 = function ($a) use ($b) {
    	    return $a + $b;
    	};
    	echo '<br>';
    	echo ($fn1(3)).'<br>';
    	echo ($fn2(3));
    	//The functions $fn1 and $fn2 behave the same.
    ?>
    
  • It is also valid in the case of nested arrow functions.

    <?php
        $c = 3;
        $fn = fn($a) => fn($b) => $a * $b * $c;
        echo $fn(1)(2); //Operation result 6
    ?>
    
  • Like anonymous functions, the arrow function syntax also allows standard function declarations, including parameters and return types, default values, variables, and passing and returning by reference. The following are effective examples of arrow functions.

    <?php
        fn($a) => $a;
    	fn($a = 1) => $a;
        fn(array $a) => $a;
        static fn(): int => $a;
        fn(&$a) => $a;
        fn&($a) => $a;
        fn($a, ...$b) => $b;
    ?>
    
  • The arrow function will automatically bind the context variable, which is equivalent to each variable used inside the arrow function x Hold that 's ok Yes one individual ' u s e ( x executed a ` use( X executed a 'use(x)'. This means that it is impossible to modify any value of the external scope. To modify the value, you can use anonymous functions instead.

    <?php
        $a = 1;
        $fn = fn() => $a++; // $a + + does not affect the value of $a
        $fn();
        echo $a;  // Result 1
    ?>
    
  • You can use func with arrow functions_ num_ args(), func_ get_ Arg (), and func_get_args() function.

Topics: PHP