About PHP method parameters

Time:2022-1-13

In all programming languages, methods or functions can pass some parameters to process or calculate business logic. This is nothing to say, but in PHP, method parameters have many interesting capabilities. Let’s talk about this.

reference parameter

It involves value passing and reference passing. Under normal circumstances, when we use value transfer, variables are copied, and variables inside and outside the method will not share memory. That is, if the value of the variable is modified in the method body, the variables outside the method will not change. Reference passing is the memory value of the passed variable. Variables inside and outside the method can be regarded as the same variable, for example:

$a = 1;
function test(&$arg){
    $arg++;
}
test($a);
echo $a; // 2

Adding the & identifier to the parameter indicates that the parameter is passed by reference. If this identifier is not added, all basic type parameters will be passed as values. Why emphasize basic types? Let’s use class as a parameter to test:

class A
{
    public $a = 1;
}
function testA($obj)
{
    $obj->a++;
}

$o = new A();
testA($o);
echo $o->a; // 2

In this example, we do not use the & flag to indicate that the parameter $obj is of reference type, but if the passed parameter is an object, it is passed by reference by default. What if you want objects to be passed by value? Sorry, it can’t be implemented in method parameters. You can only clone object parameters in the method body.

class A
{
    public $a = 1;
}
function testA($obj)
{
    $o = clone $obj;
    $o->a++;
}
$o = new A();
testA($o);
echo $o->a; // 1

For values and references, refer to the explanation of prototype pattern in design pattern:
Prototype pattern of PHP design pattern

Default parameters

Parameters can have default values. I think everyone should be very clear about this. However, it should also be noted that the default parameters should not be put in front, otherwise it is easy to make mistakes, such as:

function testArgsA($a = 1, $b){
    echo $a+$b;
}

testArgs(); // error

function testArgsB($a = 1, $b = 2){
    echo $a+$b;
}

testArgsB(); // 3

function testArgsC($a, $b = 2){
    echo $a+$b;
}

testArgsC(1); // 3

In complex functions or urgent business development, it is likely that a parameter will be omitted accidentally. At this time, testargsa will return an error. Of course, such careless mistakes should be avoided as much as possible.

When specifying the default value, we should specify it according to the type of the parameter. For example, the string is specified as’ ‘, and the number is specified as the number type. When you are not sure what type the parameter is, it is recommended to use null as the default parameter.

function testArgsD($a = NULL)
{
    if ($a) {
        echo $a;
    }
}

testArgsD(1);
testArgsD('a');

Type declaration

Type declaration is a function added after PHP 5. Just like Java, the type of the parameter is added before the parameter, such as:

function testAssignA(int $a = 0)
{
    echo $a;
}

testAssignA(1);
testAssignA("a"); // error

If the parameter type is wrong, an error will be reported directly. Before php7, only class, array and anonymous method type declarations were supported. After php7, all common types are supported, but it should be noted that only the fixed writing of common types is supported.

  • Class/interface name
  • self
  • array
  • callable
  • bool
  • float
  • int
  • string

What does fixed writing mean?

function testAssignB(integer $a = 0) // error
{
    echo $a;
}

In other words, int can only write int, integer cannot be used, and Boolean cannot be used for Boolean. Can only be type keywords listed above.

What are the benefits of type declarations? In fact, it is the difference between Java, a static language, and PHP, a dynamic language. The advantage of dynamic type language is that variables are flexible without specifying types, which is convenient for rapid development iteration. But the problem also lies in flexibility. In order to be flexible, dynamic languages often automatically type convert variables during comparison or calculation. If you don’t have a clear understanding of variable type conversion, it’s easy to have various types of bugs. At the same time, statically typed languages generally have compilation and packaging, while dynamically typed languages determine the variable type during execution, so they rarely compile and package, and their operation efficiency is not as high as that of compiled languages such as Java.

For the type conversion of PHP, please refer to the previous article:
Cast in PHP

Tips is a trick. If a parameter type is declared, null value cannot be passed, such as:

function testAssignC(string $a = '')
{
    if ($a) {
        echo __FUNCTION__ . ':' . $a;
    }
}

testAssignC(NULL); // TypeError

There are two ways to solve this problem. One is to specify the default value = null, and the other is to use “null”? Operator:

function testAssignD(string $a = NULL)
{
    if ($a == NULL) {
        echo 'null';
    }
}

testAssignD(NULL); // null


function testAssignE(?string $a)
{
    if ($a == NULL) {
        echo 'null';
    }
}
testAssignE(NULL); // null

Variable quantity parameter

Methods in PHP can receive a variable number of parameters, such as:

function testMultiArgsA($a)
{
    var_dump(func_get_arg(2));
    var_dump(func_get_args());
    var_dump(func_num_args());
    echo $a;
}

testMultiArgsA(1, 2, 3, 4);

We only defined one parameter $a, but passed in four parameters. At this time, we can use three methods to obtain all parameters:

  • func_ get_ Arg (int $arg_num) to get the parameter at a specified position in the parameter list
  • func_ get_ Args(), get parameter list
  • func_ num_ Args(), get the number of parameters

In addition, PHP also provides Operator, used to define variable length parameters into a parameter variable, such as:

function testMultiArgsB($a, ...$b)
{
    var_dump(func_get_arg(2));
    var_dump(func_get_args());
    var_dump(func_num_args());
    echo $a;
    var_ dump($b); //  Other than $a
}

testMultiArgsB(1, 2, 3, 4);

Like the default value of the parameter, when there are multiple parameters$ B should not be placed in the front, so that the subsequent parameters will not have values, and all parameters will be in $B. But PHP has solved this problem by default, if If there are parameters after the parameters, an error will be reported directly.

Using this operator, we can also easily unpack some arrays or iteratable objects to method parameters, such as:

function testMultiArgsC($a, $b){
    echo $a, $b;
}

testMultiArgsC(...[1, 2]);

Isn’t it interesting, so what is the effect of using this feature to merge an array?

$array1 = [[1],[2],[3]];
$array2 = [4];
$array3 = [[5],[6],[7]];

$result = array_merge(...$array1); // Legal, of course: $result == [1,2,3];
print_r($result);
$result = array_merge($array2, ...$array1); // $result == [4,1,2,3]
print_r($result);
$result = array_merge(...$array1, $array2); // Fatal error: Cannot use positional argument after argument unpacking.
$result = array_merge(...$array1, ...$array3); // Legal! $result == [1,2,3,5,6,7]
print_r($result);

As when a method declares parameters, it is used externally When an operator passes parameters to a method, it cannot be in There are other parameters later, so array_ The operation of merge (… $array1, $array2) will report an error.

Test code:
https://github.com/zhangyue0503/dev-blog/blob/master/php/201911/source/PHP%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E7%9A%84%E9%82%A3%E7%82%B9%E4%BA%8B%E5%84%BF.php

Reference documents:
https://www.php.net/manual/zh/functions.arguments.php
https://www.php.net/manual/zh/functions.arguments.php#121579
https://www.php.net/manual/zh/functions.arguments.php#120580

Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532

Recommended Today

Download, installation and environment configuration of JDK

JDK Download Recommended Oracle official website:Java Software | Oracle The latest version of JDK or jdk8 is recommended here JDK installation JDK environment construction Install configuration jdk8 Right click my computer, click properties to find advanced system configuration, and then click environment variables JAVA_ HOME=C:\Program Files\java\jdk1. 8.0_ 301 // here is the path of the […]