[PHP code audit] PHP function

Welcome new students
... ...
If you are nameless, you can concentrate on practicing sword

I am not a salted fish, but a dead fish!

User defined function

definition

A function can be defined by the following syntax:

<?php
function foo($arg1, ..., $argn)
{
    //do something
    return $retval;
}

Naming conventions

The naming rules for function names and other identifiers in PHP are the same. Valid function names begin with a letter or underscore followed by a letter, number, or underscore.

Function must be defined before calling

<?php

function actionA()
{
    echo "A";
}

actionA();//Can call
actionB();//Can call

function actionB()
{
    echo "B";
}

Execution results:

Calling function in function

<?php

function actionA()
{
  function actionB()
  {
      echo "B";
  }
}

actionB();//Cannot call
actionA();//Define function actionB()
actionB();//Can call

Execution results:


PHP does not support function overloading, nor is it possible to undefine or redefine declared functions

<?php

function sayHi()
{
    echo 'Hi';
}
function sayHi()
{
    echo 'Hello';
}
sayHi();//An error is reported. The function sayHi() cannot be redefined

Execution results:


The function name is case independent, but when calling a function, it usually uses the same form as it was defined.

Recursive function

The essence of recursive function is to call the function itself, but to avoid recursive function / method, call more than 100-200 layers, because it may crash the stack and terminate the current script. Infinite recursion can be considered a programming error.

<?php
function recursion($a)
{
    if ($a < 20) {
        echo "$a\n";
        recursion($a + 1);
    }
}

Execution results:

Parameters of function

Through the parameter list, you can pass information to the function, that is, a list of expressions separated by commas.

PHP supports passing parameters by value (default), passing parameters and default parameters by reference. Variable number of parameters are also supported;

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. If you want a parameter of a function to be always passed by reference, you can prefix the parameter in the function definition with the symbol &:

<?php
function actionB(&$string)
{
    $string .= 'and something extra.';
}
$str = 'This is a string, ';
actionB($str);
echo $str;    // outputs 'This is a string, and something extra.'
?> 

Execution results:


The value of the default parameter

The function can define the default values of scalar parameters in C + + style, as follows:

<?php
function makecoffee($type = "cappuccino")
{
    return "Making a cup of $type.\n";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?> 

Execution results:

Return value

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.

return

<?php
function square($num)
{
    return $num * $num;
}
echo square(4);   // outputs '16'.

Execution results:


The function cannot return multiple values, but you can get a similar effect by returning an array.

Returns an array to get multiple return values

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

To return a reference from a function, you must use the reference operator &:

Returns a reference from a function

<?php
function &returns_reference()
{
    return $someref;
}

$newref =& returns_reference();
?> 

Return value type declaration

PHP 7 adds support for return type declarations. Similar to the parameter type declaration, the return type declaration indicates the type of return value of the function. The available types are the same as those available in the parameter declaration.

<?php

function arraysSum(array ...$arrays): array
{
    return array_map(function(array $array): int {
        return array_sum($array);
    }, $arrays);
}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

The above routine will output:

Array
(
    [0] => 6
    [1] => 15
    [2] => 24
)

**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 try to execute it. Variable functions can be used to achieve some purposes, including callback functions and function tables.

Variable functions cannot be used in language structures, such as echo, print, unset(), isset(), empty(), include, require and similar statements. You need to use your own wrapper functions to use these structures as variable functions**

<?php

class Test
{
    public static $actionB = "property B";

    public function actionA()
    {
        echo "method A";
    }
    public static function actionB()
    {
        echo "method B";
    }
}

function sayHi() {
    echo "Hi".PHP_EOL;
}

function sayHello($word = '') {
    echo "Hello $word";
}


$func = 'sayHi';
$func();

$func = 'sayHello';
$func('World');

$func = 'actionA';
(new Test())->$func();

echo Test::$actionB;
$actionB = 'actionB';
Test::$actionB();

Execution results:

  • You can use the syntax of variable functions to call an object method and a static method
  • Static method calls take precedence over property calls

Internal function

Also known as 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 mysql_ For the connect () function, you need to add MySQL support when compiling PHP.

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. PHP manuals organize their documentation according to different extension libraries.

Note: if the parameter type passed to the function is inconsistent with the actual type, such as passing an array to a variable of string type, the return value of the function is uncertain. In this case, the function usually returns NULL. But this is just a convention, not necessarily so.

See function_exists(), function reference, get_extension_funcs() and dl().

Anonymous function

Anonymous functions, also known as closures, allow you to temporarily create a function without a specified name. The value most often used as a callback function parameter. Of course, there are other applications.

Anonymous functions are currently implemented through the Closure class.

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// Output helloWorld

Execution results:


Closure functions can also be used as values of variables. 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 function variable assignment

<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');

Execution results:

Inherit variables from parent scope

Closures can inherit variables from the parent scope. Any such variable should be passed in using the use language structure. Since PHP 7.1, you cannot pass in such variables as superglobals, $this, or the same name as the parameter.

<?php
$msg = 'hello';

$a = function () {
    var_dump($msg);
};
$a();

$b = function () use ($msg) {
    var_dump($msg);
};
$b();

$msg = 'hi';
$b();

$c = function () use (&$msg) {
    var_dump($msg);
};
$c();

$d = function ($arg) use ($msg) {
    var_dump($arg . ' ' . $msg);
};
$d("hello");

Execution results:

  • use to inherit variables from the parent scope
  • Anonymous functions inherit the parent scope variables when they are defined, not when they are called
  • If a variable is assigned by reference, the original variable will change, and the variable referencing the variable will also change

    Reference link: https://www.shiyanlou.com/courses/23

I smiled at the sky with my horizontal knife, leaving two Kunlun Mountains

Tags: Cyber Security penetration test Information Security

Posted on Mon, 27 Sep 2021 22:10:48 -0400 by cornercuttinjoe