language/functions.xml
ad7129daf0d410badf414b6707080e2451a80d1f
...
...
@@ -175,7 +175,8 @@ function recursion($a)
175
175
<simpara>
176
176
Information may be passed to functions via the argument list,
177
177
which is a comma-delimited list of expressions. The arguments are
178
-
evaluated from left to right.
178
+
evaluated from left to right, before the function is actually called
179
+
(<emphasis>eager</emphasis> evaluation).
179
180
</simpara>
180
181

181
182
<para>
...
...
@@ -226,28 +227,6 @@ function takes_many_args(
226
227
]]>
227
228
</programlisting>
228
229
</example>
229
-
<para>
230
-
As of PHP 8.0.0, passing mandatory arguments after optional arguments
231
-
is deprecated. This can generally be resolved by dropping the default value.
232
-
One exception to this rule are arguments of the form
233
-
<code>Type $param = null</code>, where the &null; default makes the type implicitly
234
-
nullable. This usage remains allowed, though it is recommended to use an
235
-
explicit nullable type instead.
236
-
</para>
237
-
<example>
238
-
<title>Passing optional arguments after mandatory arguments</title>
239
-
<programlisting role="php">
240
-
<![CDATA[
241
-
<?php
242
-
function foo($a = [], $b) {} // Before
243
-
function foo($a, $b) {} // After
244
-

245
-
function bar(A $a = null, $b) {} // Still allowed
246
-
function bar(?A $a, $b) {} // Recommended
247
-
?>
248
-
]]>
249
-
</programlisting>
250
-
</example>
251
230

252
231
<sect2 xml:id="functions.arguments.by-reference">
253
232
<title>Passing arguments by reference</title>
...
...
@@ -288,8 +267,10 @@ echo $str; // outputs 'This is a string, and something extra.'
288
267
<title>Default argument values</title>
289
268
290
269
<para>
291
-
A function may define C++-style default values for scalar
292
-
arguments as follows:
270
+
A function may define default values for arguments using syntax similar
271
+
to assigning a variable. The default is used only when the parameter is
272
+
not specified; in particular, note that passing &null; does <emphasis>not</emphasis>
273
+
assign the default value.
293
274
</para>
294
275
<para>
295
276
<example>
...
...
@@ -318,8 +299,9 @@ Making a cup of espresso.
318
299
</example>
319
300
</para>
320
301
<para>
321
-
PHP also allows the use of <type>array</type>s and the special type &null;
322
-
as default values, for example:
302
+
Default parameter values may be scalar values, <type>array</type>s,
303
+
the special type &null;, and as of PHP 8.1.0, objects using the
304
+
<link linkend="language.oop5.basic.new">new ClassName()</link> syntax.
323
305
</para>
324
306
<para>
325
307
<example>
...
...
@@ -333,21 +315,61 @@ function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
333
315
return "Making a cup of ".join(", ", $types)." with $device.\n";
334
316
}
335
317
echo makecoffee();
336
-
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
337
-
?>
318
+
echo makecoffee(array("cappuccino", "lavazza"), "teapot");?>
338
319
]]>
339
320
</programlisting>
321
+
&example.outputs;
322
+
<screen>
323
+
<![CDATA[
324
+
Making a cup of cappuccino with hands.
325
+
Making a cup of cappuccino, lavazza with teapot.
326
+
]]>
327
+
</screen>
340
328
</example>
329
+
</para>
330
+
<para>
331
+
<example>
332
+
<title>Using objects as default values (as of PHP 8.1.0)</title>
333
+
<programlisting role="php">
334
+
<![CDATA[
335
+
<?php
336
+
class DefaultCoffeeMaker {
337
+
public function brew() {
338
+
return "Making coffee.\n";
339
+
}
340
+
}
341
+
class FancyCoffeeMaker {
342
+
public function brew() {
343
+
return "Crafting a beautiful coffee just for you.\n";
344
+
}
345
+
}
346
+
function makecoffee($coffeeMaker = new DefaultCoffeeMaker)
347
+
{
348
+
return $coffeeMaker->brew();
349
+
}
350
+
echo makecoffee();
351
+
echo makecoffee(new FancyCoffeeMaker);
352
+
?>
353
+
]]>
354
+
</programlisting>
341
355

356
+
&example.outputs;
357
+
<screen>
358
+
<![CDATA[
359
+
Making coffee.
360
+
Crafting a beautiful coffee just for you.
361
+
]]>
362
+
</screen>
363
+
</example>
342
364
</para>
343
365
<simpara>
344
366
The default value must be a constant expression, not (for
345
367
example) a variable, a class member or a function call.
346
368
</simpara>
347
369
<para>
348
-
Note that when using default arguments, any defaults should be on
349
-
the right side of any non-default arguments; otherwise, things
350
-
will not work as expected. Consider the following code snippet:
370
+
Note that any optional arguments should be specified after any
371
+
required arguments, otherwise they cannot be omitted from calls.
372
+
Consider the following example:
351
373
</para>
352
374
<para>
353
375
<example>
...
...
@@ -355,21 +377,20 @@ echo makecoffee(array("cappuccino", "lavazza"), "teapot");
355
377
<programlisting role="php">
356
378
<![CDATA[
357
379
<?php
358
-
function makeyogurt($type = "acidophilus", $flavour)
380
+
function makeyogurt($container = "bowl", $flavour)
359
381
{
360
-
return "Making a bowl of $type $flavour.\n";
382
+
return "Making a $container of $flavour yogurt.\n";
361
383
}
362
384
363
-
echo makeyogurt("raspberry"); // won't work as expected
385
+
echo makeyogurt("raspberry"); // "raspberry" is $container, not $flavour
364
386
?>
365
387
]]>
366
388
</programlisting>
367
389
&example.outputs;
368
390
<screen>
369
391
<![CDATA[
370
-
Warning: Missing argument 2 in call to makeyogurt() in
371
-
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
372
-
Making a bowl of raspberry .
392
+
Fatal error: Uncaught ArgumentCountError: Too few arguments
393
+
to function makeyogurt(), 1 passed in example.php on line 42
373
394
]]>
374
395
</screen>
375
396
</example>
...
...
@@ -383,23 +404,80 @@ Making a bowl of raspberry .
383
404
<programlisting role="php">
384
405
<![CDATA[
385
406
<?php
386
-
function makeyogurt($flavour, $type = "acidophilus")
407
+
function makeyogurt($flavour, $container = "bowl")
408
+
{
409
+
return "Making a $container of $flavour yogurt.\n";
410
+
}
411
+
412
+
echo makeyogurt("raspberry"); // "raspberry" is $flavour
413
+
?>
414
+
]]>
415
+
</programlisting>
416
+
&example.outputs;
417
+
<screen>
418
+
<![CDATA[
419
+
Making a bowl of raspberry yogurt.
420
+
]]>
421
+
</screen>
422
+
</example>
423
+
</para>
424
+
<para>
425
+
As of PHP 8.0.0, <link linkend="functions.named-arguments">named arguments</link>
426
+
can be used to skip over multiple optional parameters.
427
+
</para>
428
+
<para>
429
+
<example>
430
+
<title>Correct usage of default function arguments</title>
431
+
<programlisting role="php">
432
+
<![CDATA[
433
+
<?php
434
+
function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek")
387
435
{
388
-
return "Making a bowl of $type $flavour.\n";
436
+
return "Making a $container of $flavour $style yogurt.\n";
389
437
}
390
438

391
-
echo makeyogurt("raspberry"); // works as expected
439
+
echo makeyogurt(style: "natural");
392
440
?>
393
441
]]>
394
442
</programlisting>
395
443
&example.outputs;
396
444
<screen>
397
445
<![CDATA[
398
-
Making a bowl of acidophilus raspberry.
446
+
Making a bowl of raspberry natural yogurt.
399
447
]]>
400
448
</screen>
401
449
</example>
402
450
</para>
451
+
<para>
452
+
As of PHP 8.0.0, declaring mandatory arguments after optional arguments
453
+
is <emphasis>deprecated</emphasis>. This can generally be resolved by
454
+
dropping the default value, since it will never be used.
455
+
One exception to this rule are arguments of the form
456
+
<code>Type $param = null</code>, where the &null; default makes the type implicitly
457
+
nullable. This usage remains allowed, though it is recommended to use an
458
+
explicit <link linkend="language.types.declarations.nullable">nullable type</link> instead.
459
+
<example>
460
+
<title>Declaring optional arguments after mandatory arguments</title>
461
+
<programlisting role="php">
462
+
<![CDATA[
463
+
<?php
464
+
function foo($a = [], $b) {} // Default not used; deprecated as of PHP 8.0.0
465
+
function foo($a, $b) {} // Functionally equivalent, no deprecation notice
466
+

467
+
function bar(A $a = null, $b) {} // Still allowed; $a is required but nullable
468
+
function bar(?A $a, $b) {} // Recommended
469
+
?>
470
+
]]>
471
+
</programlisting>
472
+
</example>
473
+
</para>
474
+
<note>
475
+
<simpara>
476
+
As of PHP 7.1.0, omitting a parameter which does not specify a default
477
+
throws an <classname>ArgumentCountError</classname>; in previous versions
478
+
it raised a Warning.
479
+
</simpara>
480
+
</note>
403
481
<note>
404
482
<simpara>
405
483
Arguments that are passed by reference may have a default value.
...
...
@@ -416,22 +494,11 @@ Making a bowl of acidophilus raspberry.
416
494
<literal>...</literal> token.
417
495
</simpara>
418
496

419
-
<note>
420
-
<simpara>
421
-
It is also possible to achieve variable-length arguments by using
422
-
<function>func_num_args</function>,
423
-
<function>func_get_arg</function>, and
424
-
<function>func_get_args</function> functions.
425
-
This technique is not recommended as it was used prior to the introduction
426
-
of the <literal>...</literal> token.
427
-
</simpara>
428
-
</note>
429
-

430
497
<para>
431
498
Argument lists may include the
432
499
<literal>...</literal> token to denote that the function accepts a
433
500
variable number of arguments. The arguments will be passed into the
434
-
given variable as an array; for example:
501
+
given variable as an &array;:
435
502

436
503
<example>
437
504
<title>Using <literal>...</literal> to access variable arguments</title>
...
...
@@ -501,7 +568,7 @@ echo add(...$a);
501
568
It is also possible to add a
502
569
<link linkend="language.types.declarations">type declaration</link> before the
503
570
<literal>...</literal> token. If this is present, then all arguments
504
-
captured by <literal>...</literal> must be objects of the hinted class.
571
+
captured by <literal>...</literal> must match that parameter type.
505
572

506
573
<example>
507
574
<title>Type declared variable arguments</title>
...
...
@@ -542,46 +609,6 @@ Catchable fatal error: Argument 2 passed to total_intervals() must be an instanc
542
609
(<literal>&amp;</literal>).
543
610
</para>
544
611

545
-
<sect3 xml:id="functions.variable-arg-list.old">
546
-
<title>Older versions of PHP</title>
547
-

548
-
<para>
549
-
No special syntax is required to note that a function is variadic;
550
-
however access to the function's arguments must use
551
-
<function>func_num_args</function>, <function>func_get_arg</function>
552
-
and <function>func_get_args</function>.
553
-
</para>
554
-

555
-
<para>
556
-
The first example above would be implemented as follows in old versions of PHP:
557
-

558
-
<example>
559
-
<title>Accessing variable arguments in old PHP versions</title>
560
-
<programlisting role="php">
561
-
<![CDATA[
562
-
<?php
563
-
function sum() {
564
-
$acc = 0;
565
-
foreach (func_get_args() as $n) {
566
-
$acc += $n;
567
-
}
568
-
return $acc;
569
-
}
570
-

571
-
echo sum(1, 2, 3, 4);
572
-
?>
573
-
]]>
574
-
</programlisting>
575
-
&example.outputs;
576
-
<screen>
577
-
<![CDATA[
578
-
10
579
-
]]>
580
-
</screen>
581
-
</example>
582
-
</para>
583
-
</sect3>
584
-

585
612
</sect2>
586
613

587
614
<sect2 xml:id="functions.named-arguments">
...
...
@@ -605,7 +632,7 @@ echo sum(1, 2, 3, 4);
605
632
<example>
606
633
<title>Named argument syntax</title>
607
634
<programlisting role="php">
608
-
<![CDATA[
635
+
<![CDATA[
609
636
<?php
610
637
myFunction(paramName: $value);
611
638
array_foobar(array: $value);
...
...
@@ -620,7 +647,7 @@ function_name($variableStoringParamName: $value);
620
647
<example>
621
648
<title>Positional arguments versus named arguments</title>
622
649
<programlisting role="php">
623
-
<![CDATA[
650
+
<![CDATA[
624
651
<?php
625
652
// Using positional arguments:
626
653
array_fill(0, 100, 50);
...
...
@@ -639,7 +666,7 @@ array_fill(start_index: 0, count: 100, value: 50);
639
666
<example>
640
667
<title>Same example as above with a different order of parameters</title>
641
668
<programlisting role="php">
642
-
<![CDATA[
669
+
<![CDATA[
643
670
<?php
644
671
array_fill(value: 50, count: 100, start_index: 0);
645
672
?>
...
...
@@ -657,11 +684,11 @@ array_fill(value: 50, count: 100, start_index: 0);
657
684
<example>
658
685
<title>Combining named arguments with positional arguments</title>
659
686
<programlisting role="php">
660
-
<![CDATA[
687
+
<![CDATA[
661
688
<?php
662
689
htmlspecialchars($string, double_encode: false);
663
690
// Same as
664
-
htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
691
+
htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false);
665
692
?>
666
693
]]>
667
694
</programlisting>
...
...
@@ -672,9 +699,9 @@ htmlspecialchars($string, ENT_COMPAT | ENT_HTML401, 'UTF-8', false);
672
699
</para>
673
700

674
701
<example>
675
-
<title>Error exception when passing the same parameter multiple times</title>
702
+
<title>Error thrown when passing the same parameter multiple times</title>
676
703
<programlisting role="php">
677
-
<![CDATA[
704
+
<![CDATA[
678
705
<?php
679
706
function foo($param) { ... }
680
707

...
...
@@ -687,6 +714,29 @@ foo(1, param: 2);
687
714
</programlisting>
688
715
</example>
689
716

717
+
<para>
718
+
As of PHP 8.1.0, it is possible to use named arguments after unpacking the arguments.
719
+
A named argument <emphasis>must not</emphasis> override an already unpacked argument.
720
+
</para>
721
+

722
+
<example>
723
+
<title>Use named arguments after unpacking</title>
724
+
<programlisting role="php">
725
+
<![CDATA[
726
+
<?php
727
+
function foo($a, $b, $c = 3, $d = 4) {
728
+
return $a + $b + $c + $d;
729
+
}
730
+

731
+
var_dump(foo(...[1, 2], d: 40)); // 46
732
+
var_dump(foo(...['b' => 2, 'a' => 1], d: 40)); // 46
733
+

734
+
var_dump(foo(...[1, 2], b: 20)); // Fatal error. Named parameter $b overwrites previous argument
735
+
?>
736
+
]]>
737
+
</programlisting>
738
+
</example>
739
+

690
740
</sect2>
691
741
</sect1>
692
742
...
...
@@ -974,8 +1024,42 @@ $func(); // prints "bar"
974
1024
the return value of the function is undefined. In this case it will
975
1025
likely return &null; but this is just a convention, and cannot be relied
976
1026
upon.
1027
+
As of PHP 8.0.0, a <classname>TypeError</classname> exception is supposed to
1028
+
be thrown in this case.
977
1029
</simpara>
978
1030
</note>
1031
+
<note>
1032
+
<para>
1033
+
Scalar types for built-in functions are nullable by default in coercive mode.
1034
+
As of PHP 8.1.0, passing &null; to an internal function parameter that is not declared nullable
1035
+
is discouraged and emits a deprecation notice in coercive mode to align with the behavior of user-defined functions,
1036
+
where scalar types need to be marked as nullable explicitly.
1037
+
</para>
1038
+

1039
+
<para>
1040
+
For example, <function>strlen</function> function expects the parameter <literal>$string</literal>
1041
+
to be a non-nullable &string;.
1042
+
For historical reasons, PHP allows passing &null; for this parameter in coercive mode, and the parameter is
1043
+
implicitly cast to <type>string</type>, resulting in a <literal>""</literal> value.
1044
+
In contrast, a <classname>TypeError</classname> is emitted in strict mode.
1045
+
</para>
1046
+

1047
+
<example>
1048
+
<programlisting role="php">
1049
+
<![CDATA[
1050
+
<?php
1051
+
var_dump(strlen(null));
1052
+
// "Deprecated: Passing null to parameter #1 ($string) of type string is deprecated" as of PHP 8.1.0
1053
+
// int(0)
1054
+

1055
+
var_dump(str_contains("foobar", null));
1056
+
// "Deprecated: Passing null to parameter #2 ($needle) of type string is deprecated" as of PHP 8.1.0
1057
+
// bool(true)
1058
+
?>
1059
+
]]>
1060
+
</programlisting>
1061
+
</example>
1062
+
</note>
979
1063

980
1064
<sect2 role="seealso">
981
1065
&reftitle.seealso;
...
...
@@ -1031,8 +1115,7 @@ echo preg_replace_callback('~-([a-z])~', function ($match) {
1031
1115
<programlisting role="php">
1032
1116
<![CDATA[
1033
1117
<?php
1034
-
$greet = function($name)
1035
-
{
1118
+
$greet = function($name) {
1036
1119
printf("Hello %s\r\n", $name);
1037
1120
};
1038
1121

...
...
@@ -1048,6 +1131,8 @@ $greet('PHP');
1048
1131
variables must be passed to the <literal>use</literal> language construct.
1049
1132
As of PHP 7.1, these variables must not include &link.superglobals;,
1050
1133
<varname>$this</varname>, or variables with the same name as a parameter.
1134
+
A return type declaration of the function has to be placed
1135
+
<emphasis>after</emphasis> the <literal>use</literal> clause.
1051
1136
</simpara>
1052
1137

1053
1138
<example>
...
...
@@ -1093,6 +1178,12 @@ $example = function ($arg) use ($message) {
1093
1178
var_dump($arg . ' ' . $message);
1094
1179
};
1095
1180
$example("hello");
1181
+

1182
+
// Return type declaration comes after the use clause
1183
+
$example = function () use ($message): string {
1184
+
return "hello $message";
1185
+
};
1186
+
var_dump($example());
1096
1187
?>
1097
1188
]]>
1098
1189
</programlisting>
...
...
@@ -1106,6 +1197,7 @@ string(5) "hello"
1106
1197
string(5) "hello"
1107
1198
string(5) "world"
1108
1199
string(11) "hello world"
1200
+
string(11) "hello world"
1109
1201
]]>
1110
1202
</screen>
1111
1203
</example>
...
...
@@ -1273,7 +1365,7 @@ NULL
1273
1365
$func = static function() {
1274
1366
// function body
1275
1367
};
1276
-
$func = $func->bindTo(new StdClass);
1368
+
$func = $func->bindTo(new stdClass);
1277
1369
$func();
1278
1370

1279
1371
?>
...
...
@@ -1492,6 +1584,127 @@ var_export($x); // Outputs 1
1492
1584
</sect2>
1493
1585
</sect1>
1494
1586

1587
+
<sect1 xml:id="functions.first_class_callable_syntax">
1588
+
<title>First class callable syntax</title>
1589
+

1590
+
<para>
1591
+
The first class callable syntax is introduced as of PHP 8.1.0, as a way of creating <link linkend="functions.anonymous">anonymous functions</link> from <link linkend="language.types.callable">callable</link>.
1592
+
It supersedes existing callable syntax using strings and arrays.
1593
+
The advantage of this syntax is that it is accessible to static analysis, and uses the scope at the point where the callable is acquired.
1594
+
</para>
1595
+

1596
+
<para>
1597
+
<code>CallableExpr(...)</code> syntax is used to create a <classname>Closure</classname> object from callable. <code>CallableExpr</code> accepts any expression that can be directly called in the PHP grammar:
1598
+
<example>
1599
+
<title>Simple first class callable syntax</title>
1600
+
<programlisting role="php">
1601
+
<![CDATA[
1602
+
<?php
1603
+

1604
+
class Foo {
1605
+
public function method() {}
1606
+
public static function staticmethod() {}
1607
+
public function __invoke() {}
1608
+
}
1609
+

1610
+
$obj = new Foo();
1611
+
$classStr = 'Foo';
1612
+
$methodStr = 'method';
1613
+
$staticmethodStr = 'staticmethod';
1614
+

1615
+

1616
+
$f1 = strlen(...);
1617
+
$f2 = $obj(...); // invokable object
1618
+
$f3 = $obj->method(...);
1619
+
$f4 = $obj->$methodStr(...);
1620
+
$f5 = Foo::staticmethod(...);
1621
+
$f6 = $classStr::$staticmethodStr(...);
1622
+

1623
+
// traditional callable using string, array
1624
+
$f7 = 'strlen'(...);
1625
+
$f8 = [$obj, 'method'](...);
1626
+
$f9 = [Foo::class, 'staticmethod'](...);
1627
+
?>
1628
+
]]>
1629
+
</programlisting>
1630
+
</example>
1631
+
</para>
1632
+

1633
+
<note>
1634
+
<para>
1635
+
The <code>...</code> is part of the syntax, and not an omission.
1636
+
</para>
1637
+
</note>
1638
+

1639
+
<para>
1640
+
<code>CallableExpr(...)</code> has the same semantics as <methodname>Closure::fromCallable</methodname>.
1641
+
That is, unlike callable using strings and arrays, <code>CallableExpr(...)</code> respects the scope at the point where it is created:
1642
+
<example>
1643
+
<title>Scope comparison of <code>CallableExpr(...)</code> and traditional callable</title>
1644
+
<programlisting role="php">
1645
+
<![CDATA[
1646
+
<?php
1647
+

1648
+
class Foo {
1649
+
public function getPrivateMethod() {
1650
+
return [$this, 'privateMethod'];
1651
+
}
1652
+

1653
+
private function privateMethod() {
1654
+
echo __METHOD__, "\n";
1655
+
}
1656
+
}
1657
+

1658
+
$foo = new Foo;
1659
+
$privateMethod = $foo->getPrivateMethod();
1660
+
$privateMethod();
1661
+
// Fatal error: Call to private method Foo::privateMethod() from global scope
1662
+
// This is because call is performed outside from Foo and visibility will be checked from this point.
1663
+

1664
+
class Foo1 {
1665
+
public function getPrivateMethod() {
1666
+
// Uses the scope where the callable is acquired.
1667
+
return $this->privateMethod(...); // identical to Closure::fromCallable([$this, 'privateMethod']);
1668
+
}
1669
+

1670
+
private function privateMethod() {
1671
+
echo __METHOD__, "\n";
1672
+
}
1673
+
}
1674
+

1675
+
$foo1 = new Foo1;
1676
+
$privateMethod = $foo1->getPrivateMethod();
1677
+
$privateMethod(); // Foo1::privateMethod
1678
+
?>
1679
+
]]>
1680
+
</programlisting>
1681
+
</example>
1682
+

1683
+
</para>
1684
+

1685
+
<note>
1686
+
<para>
1687
+
Object creation by this syntax (e.g <code>new Foo(...)</code>) is not supported, because <code>new Foo()</code> syntax is not considered a call.
1688
+
</para>
1689
+
</note>
1690
+

1691
+
<note>
1692
+
<para>
1693
+
The first-class callable syntax cannot be combined with the <link linkend="language.oop5.basic.nullsafe">nullsafe operator</link>. Both of the following result in a compile-time error:
1694
+
<example>
1695
+
<programlisting role="php">
1696
+
<![CDATA[
1697
+
<?php
1698
+
$obj?->method(...);
1699
+
$obj?->prop->method(...);
1700
+
?>
1701
+
]]>
1702
+
</programlisting>
1703
+
</example>
1704
+
</para>
1705
+
</note>
1706
+
</sect1>
1707
+

1495
1708
</chapter>
1496
1709
1497
1710
<!-- Keep this comment at the end of the file
1498
1711