/
PHP方法参数的那点事儿.php
136 lines (106 loc) · 2 KB
/
PHP方法参数的那点事儿.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
<?php
$a = 1;
function test(&$arg)
{
$arg++;
}
test($a);
echo $a; // 2
class A
{
public $a = 1;
}
function testA($obj)
{
$o = clone $obj;
$o->a++;
}
$o = new A();
testA($o);
echo $o->a; // 2
// function testArgsA($a = 1, $b){
// echo $a+$b;
// }
// testArgs();
function testArgsB($a = 1, $b = 2)
{
echo $a + $b;
}
testArgsB();
function testArgsC($a, $b = 2)
{
echo $a + $b;
}
testArgsC(1);
function testArgsD($a = null)
{
if ($a) {
echo $a;
}
}
testArgsD(1);
testArgsD('a');
function testAssignA(int $a = 0)
{
echo $a;
}
testAssignA(1);
// testAssignA("a"); // error
// function testAssignB(integer $a = 0)
// {
// echo $a;
// }
function testAssignC(string $a = '')
{
if ($a) {
echo __FUNCTION__ . ':' . $a;
}
}
testAssignC(); //
// testAssignC(NULL); //TypeError
testAssignC(1); // testAssignC:a
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
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);
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); // 除$a以外的
}
testMultiArgsB(1, 2, 3, 4);
function testMultiArgsC($a, $b){
echo $a, $b;
}
testMultiArgsC(...[1, 2]);
$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);