language/functions.xml
ad7129daf0d410badf414b6707080e2451a80d1f
...
...
@@ -36,7 +36,7 @@ function foo($arg_1, $arg_2, /* ..., */ $arg_n)
36
36
valid function name starts with a letter or underscore, followed
37
37
by any number of letters, numbers, or underscores. As a regular
38
38
expression, it would be expressed thus:
39
-
<code>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*</code>.
39
+
<code>^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$</code>.
40
40
</para>
41
41
&tip.userlandnaming;
42
42
<simpara>
...
...
@@ -126,7 +126,7 @@ bar();
126
126
</simpara>
127
127
<note>
128
128
<simpara>
129
-
Function names are case-insensitive, though it is usually good form
129
+
Function names are case-insensitive for the ASCII characters <literal>A</literal> to <literal>Z</literal>, though it is usually good form
130
130
to call functions as they appear in their declaration.
131
131
</simpara>
132
132
</note>
...
...
@@ -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>
...
...
@@ -184,7 +185,8 @@ function recursion($a)
184
185
reference</link>, and <link
185
186
linkend="functions.arguments.default">default argument
186
187
values</link>. <link linkend="functions.variable-arg-list">Variable-length
187
-
argument lists</link> are also supported.
188
+
argument lists</link> and <link linkend="functions.named-arguments">Named Arguments</link>
189
+
are also supported.
188
190
</para>
189
191
<para>
190
192
<example>
...
...
@@ -201,6 +203,31 @@ function takes_array($input)
201
203
</programlisting>
202
204
</example>
203
205
</para>
206
+
<para>
207
+
As of PHP 8.0.0, the list of function arguments may include a trailing comma, which
208
+
will be ignored. That is particularly useful in cases where the list of arguments is
209
+
long or contains long variable names, making it convenient to list arguments vertically.
210
+
</para>
211
+
<example>
212
+
<title>Function Argument List with trailing Comma</title>
213
+
<programlisting role="php">
214
+
<![CDATA[
215
+
<?php
216
+
function takes_many_args(
217
+
$first_arg,
218
+
$second_arg,
219
+
$a_very_long_argument_name,
220
+
$arg_with_default = 5,
221
+
$again = 'a default string', // This trailing comma was not permitted before 8.0.0.
222
+
)
223
+
{
224
+
// ...
225
+
}
226
+
?>
227
+
]]>
228
+
</programlisting>
229
+
</example>
230
+

204
231
<sect2 xml:id="functions.arguments.by-reference">
205
232
<title>Passing arguments by reference</title>
206
233
...
...
@@ -232,13 +259,18 @@ echo $str; // outputs 'This is a string, and something extra.'
232
259
</programlisting>
233
260
</example>
234
261
</para>
262
+
<para>
263
+
It is an error to pass a value as argument which is supposed to be passed by reference.
264
+
</para>
235
265
</sect2>
236
266
<sect2 xml:id="functions.arguments.default">
237
267
<title>Default argument values</title>
238
268
239
269
<para>
240
-
A function may define C++-style default values for scalar
241
-
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.
242
274
</para>
243
275
<para>
244
276
<example>
...
...
@@ -267,8 +299,9 @@ Making a cup of espresso.
267
299
</example>
268
300
</para>
269
301
<para>
270
-
PHP also allows the use of <type>array</type>s and the special type &null;
271
-
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.
272
305
</para>
273
306
<para>
274
307
<example>
...
...
@@ -282,511 +315,194 @@ function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
282
315
return "Making a cup of ".join(", ", $types)." with $device.\n";
283
316
}
284
317
echo makecoffee();
285
-
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
286
-
?>
287
-
]]>
288
-
</programlisting>
289
-
</example>
290
-
291
-
</para>
292
-
<simpara>
293
-
The default value must be a constant expression, not (for
294
-
example) a variable, a class member or a function call.
295
-
</simpara>
296
-
<para>
297
-
Note that when using default arguments, any defaults should be on
298
-
the right side of any non-default arguments; otherwise, things
299
-
will not work as expected. Consider the following code snippet:
300
-
</para>
301
-
<para>
302
-
<example>
303
-
<title>Incorrect usage of default function arguments</title>
304
-
<programlisting role="php">
305
-
<![CDATA[
306
-
<?php
307
-
function makeyogurt($type = "acidophilus", $flavour)
308
-
{
309
-
return "Making a bowl of $type $flavour.\n";
310
-
}
311
-
312
-
echo makeyogurt("raspberry"); // won't work as expected
313
-
?>
318
+
echo makecoffee(array("cappuccino", "lavazza"), "teapot");?>
314
319
]]>
315
320
</programlisting>
316
321
&example.outputs;
317
322
<screen>
318
323
<![CDATA[
319
-
Warning: Missing argument 2 in call to makeyogurt() in
320
-
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
321
-
Making a bowl of raspberry .
324
+
Making a cup of cappuccino with hands.
325
+
Making a cup of cappuccino, lavazza with teapot.
322
326
]]>
323
327
</screen>
324
328
</example>
325
329
</para>
326
330
<para>
327
-
Now, compare the above with this:
328
-
</para>
329
-
<para>
330
331
<example>
331
-
<title>Correct usage of default function arguments</title>
332
+
<title>Using objects as default values (as of PHP 8.1.0)</title>
332
333
<programlisting role="php">
333
334
<![CDATA[
334
335
<?php
335
-
function makeyogurt($flavour, $type = "acidophilus")
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)
336
347
{
337
-
return "Making a bowl of $type $flavour.\n";
348
+
return $coffeeMaker->brew();
338
349
}
339
-
340
-
echo makeyogurt("raspberry"); // works as expected
350
+
echo makecoffee();
351
+
echo makecoffee(new FancyCoffeeMaker);
341
352
?>
342
353
]]>
343
354
</programlisting>
355
+

344
356
&example.outputs;
345
357
<screen>
346
358
<![CDATA[
347
-
Making a bowl of acidophilus raspberry.
359
+
Making coffee.
360
+
Crafting a beautiful coffee just for you.
348
361
]]>
349
362
</screen>
350
363
</example>
351
364
</para>
352
-
<note>
353
-
<simpara>
354
-
As of PHP 5, arguments that are passed by reference may have a default value.
355
-
</simpara>
356
-
</note>
357
-
</sect2>
358
-

359
-
<sect2 xml:id="functions.arguments.type-declaration">
360
-
<title>Type declarations</title>
361
-

362
-
<note>
363
-
<para>
364
-
Type declarations were also known as type hints in PHP 5.
365
-
</para>
366
-
</note>
367
-

365
+
<simpara>
366
+
The default value must be a constant expression, not (for
367
+
example) a variable, a class member or a function call.
368
+
</simpara>
368
369
<para>
369
-
Type declarations allow functions to require that parameters are of a certain type at call time.
370
-
If the given value is of the incorrect type,
371
-
then an error is generated: in PHP 5, this will be a recoverable fatal
372
-
error, while PHP 7 will throw a <classname>TypeError</classname>
373
-
exception.
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:
374
373
</para>
375
-

376
374
<para>
377
-
To specify a type declaration, the type name should be added before the
378
-
parameter name. The declaration can be made to accept &null; values if
379
-
the default value of the parameter is set to &null;.
380
-
</para>
381
-

382
-
<sect3 xml:id="functions.arguments.type-declaration.types">
383
-
<title>Valid types</title>
384
-
<informaltable>
385
-
<tgroup cols="3">
386
-
<thead>
387
-
<row>
388
-
<entry>Type</entry>
389
-
<entry>Description</entry>
390
-
<entry>Minimum PHP version</entry>
391
-
</row>
392
-
</thead>
393
-
<tbody>
394
-
<row>
395
-
<entry>Class/interface name</entry>
396
-
<entry>
397
-
The parameter must be an &instanceof; the given class or interface
398
-
name.
399
-
</entry>
400
-
<entry>PHP 5.0.0</entry>
401
-
</row>
402
-
<row>
403
-
<entry><literal>self</literal></entry>
404
-
<entry>
405
-
The parameter must be an &instanceof; the same class as the one the
406
-
method is defined on. This can only be used on class and instance
407
-
methods.
408
-
</entry>
409
-
<entry>PHP 5.0.0</entry>
410
-
</row>
411
-
<row>
412
-
<entry><type>array</type></entry>
413
-
<entry>
414
-
The parameter must be an <type>array</type>.
415
-
</entry>
416
-
<entry>PHP 5.1.0</entry>
417
-
</row>
418
-
<row>
419
-
<entry><type>callable</type></entry>
420
-
<entry>
421
-
The parameter must be a valid <type>callable</type>.
422
-
</entry>
423
-
<entry>PHP 5.4.0</entry>
424
-
</row>
425
-
<row>
426
-
<entry><type>bool</type></entry>
427
-
<entry>
428
-
The parameter must be a <type>boolean</type> value.
429
-
</entry>
430
-
<entry>PHP 7.0.0</entry>
431
-
</row>
432
-
<row>
433
-
<entry><type>float</type></entry>
434
-
<entry>
435
-
The parameter must be a <type>float</type>ing point number.
436
-
</entry>
437
-
<entry>PHP 7.0.0</entry>
438
-
</row>
439
-
<row>
440
-
<entry><type>int</type></entry>
441
-
<entry>
442
-
The parameter must be an <type>integer</type>.
443
-
</entry>
444
-
<entry>PHP 7.0.0</entry>
445
-
</row>
446
-
<row>
447
-
<entry><type>string</type></entry>
448
-
<entry>
449
-
The parameter must be a <type>string</type>.
450
-
</entry>
451
-
<entry>PHP 7.0.0</entry>
452
-
</row>
453
-
<row>
454
-
<entry><literal>iterable</literal></entry>
455
-
<entry>
456
-
The parameter must be either an <type>array</type> or an &instanceof; <classname>Traversable</classname>.
457
-
</entry>
458
-
<entry>PHP 7.1.0</entry>
459
-
</row>
460
-
<row>
461
-
<entry><literal>object</literal></entry>
462
-
<entry>
463
-
The parameter must be an <type>object</type>.
464
-
</entry>
465
-
<entry>PHP 7.2.0</entry>
466
-
</row>
467
-
</tbody>
468
-
</tgroup>
469
-
</informaltable>
470
-

471
-
<warning>
472
-
<para>
473
-
Aliases for the above scalar types are not supported. Instead, they are
474
-
treated as class or interface names. For example, using
475
-
<literal>boolean</literal> as a parameter or return type will require
476
-
an argument or return value that is an &instanceof; the class or
477
-
interface <literal>boolean</literal>, rather than of type
478
-
<type>bool</type>:
479
-
</para>
480
-
<para>
481
-
<example>
482
-
<programlisting role="php">
483
-
<![CDATA[
484
-
<?php
485
-
function test(boolean $param) {}
486
-
test(true);
487
-
?>
488
-
]]>
489
-
</programlisting>
490
-
&example.outputs;
491
-
<screen>
492
-
<![CDATA[
493
-
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
494
-
]]>
495
-
</screen>
496
-
</example>
497
-
</para>
498
-
</warning>
499
-
</sect3>
500
-

501
-
<sect3 xml:id="functions.arguments.type-declaration.examples">
502
-
&reftitle.examples;
503
375
<example>
504
-
<title>Basic class type declaration</title>
505
-
<programlisting role="php">
506
-
<![CDATA[
507
-
<?php
508
-
class C {}
509
-
class D extends C {}
510
-

511
-
// This doesn't extend C.
512
-
class E {}
513
-

514
-
function f(C $c) {
515
-
echo get_class($c)."\n";
516
-
}
517
-

518
-
f(new C);
519
-
f(new D);
520
-
f(new E);
521
-
?>
522
-
]]>
523
-
</programlisting>
524
-
&example.outputs;
525
-
<screen>
526
-
<![CDATA[
527
-
C
528
-
D
529
-

530
-
Fatal error: Uncaught TypeError: Argument 1 passed to f() must be an instance of C, instance of E given, called in - on line 14 and defined in -:8
531
-
Stack trace:
532
-
#0 -(14): f(Object(E))
533
-
#1 {main}
534
-
thrown in - on line 8
535
-
]]>
536
-
</screen>
537
-
</example>
538
-

539
-
<example>
540
-
<title>Basic interface type declaration</title>
541
-
<programlisting role="php">
542
-
<![CDATA[
543
-
<?php
544
-
interface I { public function f(); }
545
-
class C implements I { public function f() {} }
546
-

547
-
// This doesn't implement I.
548
-
class E {}
549
-

550
-
function f(I $i) {
551
-
echo get_class($i)."\n";
552
-
}
553
-

554
-
f(new C);
555
-
f(new E);
556
-
?>
557
-
]]>
558
-
</programlisting>
559
-
&example.outputs;
560
-
<screen>
561
-
<![CDATA[
562
-
C
563
-

564
-
Fatal error: Uncaught TypeError: Argument 1 passed to f() must implement interface I, instance of E given, called in - on line 13 and defined in -:8
565
-
Stack trace:
566
-
#0 -(13): f(Object(E))
567
-
#1 {main}
568
-
thrown in - on line 8
569
-
]]>
570
-
</screen>
571
-
</example>
572
-

573
-
<example>
574
-
<title>Typed pass-by-reference Parameters</title>
575
-
<simpara>
576
-
Declared types of reference parameters are checked on function entry, but
577
-
not when the function returns, so after the function had returned, the
578
-
argument's type may have changed.
579
-
</simpara>
376
+
<title>Incorrect usage of default function arguments</title>
580
377
<programlisting role="php">
581
378
<![CDATA[
582
379
<?php
583
-
function array_baz(array &$param)
380
+
function makeyogurt($container = "bowl", $flavour)
584
381
{
585
-
$param = 1;
382
+
return "Making a $container of $flavour yogurt.\n";
586
383
}
587
-
$var = [];
588
-
array_baz($var);
589
-
var_dump($var);
590
-
array_baz($var);
591
-
?>
592
-
]]>
593
-
</programlisting>
594
-
&example.outputs.similar;
595
-
<screen>
596
-
<![CDATA[
597
-
int(1)
598
384
599
-
Fatal error: Uncaught TypeError: Argument 1 passed to array_baz() must be of the type array, int given, called in %s on line %d
600
-
]]>
601
-
</screen>
602
-
</example>
603
-
<example>
604
-
<title>Nullable type declaration</title>
605
-
<programlisting role="php">
606
-
<![CDATA[
607
-
<?php
608
-
class C {}
609
-

610
-
function f(C $c = null) {
611
-
var_dump($c);
612
-
}
613
-

614
-
f(new C);
615
-
f(null);
385
+
echo makeyogurt("raspberry"); // "raspberry" is $container, not $flavour
616
386
?>
617
387
]]>
618
388
</programlisting>
619
389
&example.outputs;
620
390
<screen>
621
391
<![CDATA[
622
-
object(C)#1 (0) {
623
-
}
624
-
NULL
392
+
Fatal error: Uncaught ArgumentCountError: Too few arguments
393
+
to function makeyogurt(), 1 passed in example.php on line 42
625
394
]]>
626
395
</screen>
627
396
</example>
628
-
</sect3>
629
-

630
-
<sect3 xml:id="functions.arguments.type-declaration.strict">
631
-
<title>Strict typing</title>
632
-

633
-
<para>
634
-
By default, PHP will coerce values of the wrong type into the expected
635
-
scalar type if possible. For example, a function that is given an
636
-
<type>integer</type> for a parameter that expects a <type>string</type>
637
-
will get a variable of type <type>string</type>.
638
-
</para>
639
-

640
-
<para>
641
-
It is possible to enable strict mode on a per-file basis. In strict
642
-
mode, only a variable of exact type of the type declaration will be
643
-
accepted, or a <classname>TypeError</classname> will be thrown. The
644
-
only exception to this rule is that an <type>integer</type> may be given
645
-
to a function expecting a <type>float</type>. Function calls from within
646
-
internal functions will not be affected by the <literal>strict_types</literal>
647
-
declaration.
648
-
</para>
649
-

650
-
<para>
651
-
To enable strict mode, the &declare; statement is used with the
652
-
<literal>strict_types</literal> declaration:
653
-
</para>
654
-

655
-
<caution>
656
-
<para>
657
-
Enabling strict mode will also affect
658
-
<link linkend="functions.returning-values.type-declaration">return type declarations</link>.
659
-
</para>
660
-
</caution>
661
-

662
-
<note>
663
-
<para>
664
-
Strict typing applies to function calls made from
665
-
<emphasis>within</emphasis> the file with strict typing enabled, not to
666
-
the functions declared within that file. If a file without strict
667
-
typing enabled makes a call to a function that was defined in a file
668
-
with strict typing, the caller's preference (weak typing) will be
669
-
respected, and the value will be coerced.
670
-
</para>
671
-
</note>
672
-

673
-
<note>
674
-
<para>
675
-
Strict typing is only defined for scalar type declarations, and as
676
-
such, requires PHP 7.0.0 or later, as scalar type declarations were
677
-
added in that version.
678
-
</para>
679
-
</note>
680
-

397
+
</para>
398
+
<para>
399
+
Now, compare the above with this:
400
+
</para>
401
+
<para>
681
402
<example>
682
-
<title>Strict typing</title>
403
+
<title>Correct usage of default function arguments</title>
683
404
<programlisting role="php">
684
405
<![CDATA[
685
406
<?php
686
-
declare(strict_types=1);
687
-

688
-
function sum(int $a, int $b) {
689
-
return $a + $b;
407
+
function makeyogurt($flavour, $container = "bowl")
408
+
{
409
+
return "Making a $container of $flavour yogurt.\n";
690
410
}
691
411
692
-
var_dump(sum(1, 2));
693
-
var_dump(sum(1.5, 2.5));
412
+
echo makeyogurt("raspberry"); // "raspberry" is $flavour
694
413
?>
695
414
]]>
696
415
</programlisting>
697
416
&example.outputs;
698
417
<screen>
699
418
<![CDATA[
700
-
int(3)
701
-

702
-
Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4
703
-
Stack trace:
704
-
#0 -(9): sum(1.5, 2.5)
705
-
#1 {main}
706
-
thrown in - on line 4
419
+
Making a bowl of raspberry yogurt.
707
420
]]>
708
421
</screen>
709
422
</example>
710
-

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>
711
429
<example>
712
-
<title>Weak typing</title>
430
+
<title>Correct usage of default function arguments</title>
713
431
<programlisting role="php">
714
432
<![CDATA[
715
433
<?php
716
-
function sum(int $a, int $b) {
717
-
return $a + $b;
434
+
function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek")
435
+
{
436
+
return "Making a $container of $flavour $style yogurt.\n";
718
437
}
719
438

720
-
var_dump(sum(1, 2));
721
-

722
-
// These will be coerced to integers: note the output below!
723
-
var_dump(sum(1.5, 2.5));
439
+
echo makeyogurt(style: "natural");
724
440
?>
725
441
]]>
726
442
</programlisting>
727
443
&example.outputs;
728
444
<screen>
729
445
<![CDATA[
730
-
int(3)
731
-
int(3)
446
+
Making a bowl of raspberry natural yogurt.
732
447
]]>
733
448
</screen>
734
449
</example>
735
-

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.
736
459
<example>
737
-
<title>Catching <classname>TypeError</classname></title>
460
+
<title>Declaring optional arguments after mandatory arguments</title>
738
461
<programlisting role="php">
739
462
<![CDATA[
740
-
<?php
741
-
declare(strict_types=1);
742
-

743
-
function sum(int $a, int $b) {
744
-
return $a + $b;
745
-
}
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
746
466

747
-
try {
748
-
var_dump(sum(1, 2));
749
-
var_dump(sum(1.5, 2.5));
750
-
} catch (TypeError $e) {
751
-
echo 'Error: '.$e->getMessage();
752
-
}
753
-
?>
754
-
]]>
467
+
function bar(A $a = null, $b) {} // Still allowed; $a is required but nullable
468
+
function bar(?A $a, $b) {} // Recommended
469
+
?>
470
+
]]>
755
471
</programlisting>
756
-
&example.outputs;
757
-
<screen>
758
-
<![CDATA[
759
-
int(3)
760
-
Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10
761
-
]]>
762
-
</screen>
763
472
</example>
764
-
</sect3>
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>
481
+
<note>
482
+
<simpara>
483
+
Arguments that are passed by reference may have a default value.
484
+
</simpara>
485
+
</note>
765
486
</sect2>
487
+

766
488
<sect2 xml:id="functions.variable-arg-list">
767
489
<title>Variable-length argument lists</title>
768
490

769
491
<simpara>
770
492
PHP has support for variable-length argument lists in
771
-
user-defined functions. This is implemented using the
772
-
<literal>...</literal> token in PHP 5.6 and later, and using the
773
-
<function>func_num_args</function>,
774
-
<function>func_get_arg</function>, and
775
-
<function>func_get_args</function> functions in PHP 5.5 and earlier.
493
+
user-defined functions by using the
494
+
<literal>...</literal> token.
776
495
</simpara>
777
496

778
-
<sect3 xml:id="functions.variable-arg-list.new">
779
-
<title><literal>...</literal> in PHP 5.6+</title>
780
-

781
-
<para>
782
-
In PHP 5.6 and later, argument lists may include the
783
-
<literal>...</literal> token to denote that the function accepts a
784
-
variable number of arguments. The arguments will be passed into the
785
-
given variable as an array; for example:
497
+
<para>
498
+
Argument lists may include the
499
+
<literal>...</literal> token to denote that the function accepts a
500
+
variable number of arguments. The arguments will be passed into the
501
+
given variable as an &array;:
786
502

787
-
<example>
788
-
<title>Using <literal>...</literal> to access variable arguments</title>
789
-
<programlisting role="php">
503
+
<example>
504
+
<title>Using <literal>...</literal> to access variable arguments</title>
505
+
<programlisting role="php">
790
506
<![CDATA[
791
507
<?php
792
508
function sum(...$numbers) {
...
...
@@ -800,24 +516,24 @@ function sum(...$numbers) {
800
516
echo sum(1, 2, 3, 4);
801
517
?>
802
518
]]>
803
-
</programlisting>
804
-
&example.outputs;
805
-
<screen>
519
+
</programlisting>
520
+
&example.outputs;
521
+
<screen>
806
522
<![CDATA[
807
523
10
808
524
]]>
809
-
</screen>
810
-
</example>
811
-
</para>
812
-

813
-
<para>
814
-
You can also use <literal>...</literal> when calling functions to unpack
815
-
an <type>array</type> or <classname>Traversable</classname> variable or
816
-
literal into the argument list:
817
-

818
-
<example>
819
-
<title>Using <literal>...</literal> to provide arguments</title>
820
-
<programlisting role="php">
525
+
</screen>
526
+
</example>
527
+
</para>
528
+

529
+
<para>
530
+
<literal>...</literal> can also be used when calling functions to unpack
531
+
an <type>array</type> or <classname>Traversable</classname> variable or
532
+
literal into the argument list:
533
+

534
+
<example>
535
+
<title>Using <literal>...</literal> to provide arguments</title>
536
+
<programlisting role="php">
821
537
<![CDATA[
822
538
<?php
823
539
function add($a, $b) {
...
...
@@ -830,33 +546,33 @@ $a = [1, 2];
830
546
echo add(...$a);
831
547
?>
832
548
]]>
833
-
</programlisting>
834
-
&example.outputs;
835
-
<screen>
549
+
</programlisting>
550
+
&example.outputs;
551
+
<screen>
836
552
<![CDATA[
837
553
3
838
554
3
839
555
]]>
840
-
</screen>
841
-
</example>
842
-
</para>
843
-

844
-
<para>
845
-
You may specify normal positional arguments before the
846
-
<literal>...</literal> token. In this case, only the trailing arguments
847
-
that don't match a positional argument will be added to the array
848
-
generated by <literal>...</literal>.
849
-
</para>
850
-

851
-
<para>
852
-
It is also possible to add a
853
-
<link linkend="language.oop5.typehinting">type hint</link> before the
854
-
<literal>...</literal> token. If this is present, then all arguments
855
-
captured by <literal>...</literal> must be objects of the hinted class.
856
-

857
-
<example>
858
-
<title>Type hinted variable arguments</title>
859
-
<programlisting role="php">
556
+
</screen>
557
+
</example>
558
+
</para>
559
+

560
+
<para>
561
+
You may specify normal positional arguments before the
562
+
<literal>...</literal> token. In this case, only the trailing arguments
563
+
that don't match a positional argument will be added to the array
564
+
generated by <literal>...</literal>.
565
+
</para>
566
+

567
+
<para>
568
+
It is also possible to add a
569
+
<link linkend="language.types.declarations">type declaration</link> before the
570
+
<literal>...</literal> token. If this is present, then all arguments
571
+
captured by <literal>...</literal> must match that parameter type.
572
+

573
+
<example>
574
+
<title>Type declared variable arguments</title>
575
+
<programlisting role="php">
860
576
<![CDATA[
861
577
<?php
862
578
function total_intervals($unit, DateInterval ...$intervals) {
...
...
@@ -875,285 +591,243 @@ echo total_intervals('d', $a, $b).' days';
875
591
echo total_intervals('d', null);
876
592
?>
877
593
]]>
878
-
</programlisting>
879
-
&example.outputs;
880
-
<screen>
594
+
</programlisting>
595
+
&example.outputs;
596
+
<screen>
881
597
<![CDATA[
882
598
3 days
883
599
Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2
884
600
]]>
885
-
</screen>
886
-
</example>
887
-
</para>
888
-

889
-
<para>
890
-
Finally, you may also pass variable arguments
891
-
<link linkend="functions.arguments.by-reference">by reference</link> by
892
-
prefixing the <literal>...</literal> with an ampersand
893
-
(<literal>&amp;</literal>).
894
-
</para>
895
-
</sect3>
896
-

897
-
<sect3 xml:id="functions.variable-arg-list.old">
898
-
<title>Older versions of PHP</title>
899
-

900
-
<para>
901
-
No special syntax is required to note that a function is variadic;
902
-
however access to the function's arguments must use
903
-
<function>func_num_args</function>, <function>func_get_arg</function>
904
-
and <function>func_get_args</function>.
905
-
</para>
906
-

907
-
<para>
908
-
The first example above would be implemented as follows in PHP 5.5 and
909
-
earlier:
910
-

911
-
<example>
912
-
<title>Accessing variable arguments in PHP 5.5 and earlier</title>
913
-
<programlisting role="php">
914
-
<![CDATA[
915
-
<?php
916
-
function sum() {
917
-
$acc = 0;
918
-
foreach (func_get_args() as $n) {
919
-
$acc += $n;
920
-
}
921
-
return $acc;
922
-
}
601
+
</screen>
602
+
</example>
603
+
</para>
923
604

924
-
echo sum(1, 2, 3, 4);
925
-
?>
926
-
]]>
927
-
</programlisting>
928
-
&example.outputs;
929
-
<screen>
930
-
<![CDATA[
931
-
10
932
-
]]>
933
-
</screen>
934
-
</example>
935
-
</para>
936
-
</sect3>
605
+
<para>
606
+
Finally, variable arguments can also be passed
607
+
<link linkend="functions.arguments.by-reference">by reference</link> by
608
+
prefixing the <literal>...</literal> with an ampersand
609
+
(<literal>&amp;</literal>).
610
+
</para>
937
611

938
612
</sect2>
939
-
</sect1>
940
613

941
-
<sect1 xml:id="functions.returning-values">
942
-
<title>Returning values</title>
614
+
<sect2 xml:id="functions.named-arguments">
615
+
<title>Named Arguments</title>
943
616

944
-
<para>
945
-
Values are returned by using the optional return statement. Any
946
-
type may be returned, including arrays and objects. This causes the
947
-
function to end its execution immediately and pass control back to
948
-
the line from which it was called. See <function>return</function>
949
-
for more information.
950
-
</para>
617
+
<para>
618
+
PHP 8.0.0 introduced named arguments as an extension of the existing
619
+
positional parameters. Named arguments allow passing arguments to a
620
+
function based on the parameter name, rather than the parameter position.
621
+
This makes the meaning of the argument self-documenting, makes the
622
+
arguments order-independent and allows skipping default values arbitrarily.
623
+
</para>
951
624

952
-
<note>
953
625
<para>
954
-
If the <function>return</function> is omitted the value &null; will be
955
-
returned.
626
+
Named arguments are passed by prefixing the value with the parameter name
627
+
followed by a colon. Using reserved keywords as parameter names is allowed.
628
+
The parameter name must be an identifier, specifying dynamically
629
+
is not allowed.
956
630
</para>
957
-
</note>
958
631

959
-
<sect2>
960
-
<title>Use of return</title>
961
-
<para>
962
632
<example>
963
-
<title>Use of <function>return</function></title>
633
+
<title>Named argument syntax</title>
964
634
<programlisting role="php">
965
635
<![CDATA[
966
636
<?php
967
-
function square($num)
968
-
{
969
-
return $num * $num;
970
-
}
971
-
echo square(4); // outputs '16'.
637
+
myFunction(paramName: $value);
638
+
array_foobar(array: $value);
639
+

640
+
// NOT supported.
641
+
function_name($variableStoringParamName: $value);
972
642
?>
973
643
]]>
974
644
</programlisting>
975
645
</example>
976
-
</para>
977
646

978
-
<para>
979
-
A function can not return multiple values, but similar results can be
980
-
obtained by returning an array.
981
-
</para>
982
-
<para>
983
647
<example>
984
-
<title>Returning an array to get multiple values</title>
648
+
<title>Positional arguments versus named arguments</title>
985
649
<programlisting role="php">
986
650
<![CDATA[
987
651
<?php
988
-
function small_numbers()
989
-
{
990
-
return array (0, 1, 2);
991
-
}
992
-
list ($zero, $one, $two) = small_numbers();
652
+
// Using positional arguments:
653
+
array_fill(0, 100, 50);
654
+

655
+
// Using named arguments:
656
+
array_fill(start_index: 0, count: 100, value: 50);
993
657
?>
994
658
]]>
995
659
</programlisting>
996
660
</example>
997
-
</para>
998
-
<para>
999
-
To return a reference from a function, use the reference operator &amp; in
1000
-
both the function declaration and when assigning the returned value to a
1001
-
variable:
1002
-
</para>
1003
-
<para>
661
+

662
+
<para>
663
+
The order in which the named arguments are passed does not matter.
664
+
</para>
665
+

1004
666
<example>
1005
-
<title>Returning a reference from a function</title>
667
+
<title>Same example as above with a different order of parameters</title>
1006
668
<programlisting role="php">
1007
669
<![CDATA[
1008
670
<?php
1009
-
function &returns_reference()
1010
-
{
1011
-
return $someref;
1012
-
}
1013
-

1014
-
$newref =& returns_reference();
671
+
array_fill(value: 50, count: 100, start_index: 0);
1015
672
?>
1016
673
]]>
1017
674
</programlisting>
1018
675
</example>
1019
-
</para>
1020
-
<simpara>
1021
-
For more information on references, please check out <link
1022
-
linkend="language.references">References Explained</link>.
1023
-
</simpara>
1024
-
</sect2>
1025
676

1026
-
<sect2 xml:id="functions.returning-values.type-declaration">
1027
-
<title>Return type declarations</title>
677
+
<para>
678
+
Named arguments can be combined with positional arguments. In this case,
679
+
the named arguments must come after the positional arguments.
680
+
It is also possible to specify only some of the optional arguments of a
681
+
function, regardless of their order.
682
+
</para>
1028
683

1029
-
<para>
1030
-
PHP 7 adds support for return type declarations. Similarly to
1031
-
<link linkend="functions.arguments.type-declaration">argument type declarations</link>,
1032
-
return type declarations specify the type of the value that will be
1033
-
returned from a function. The same
1034
-
<link linkend="functions.arguments.type-declaration.types">types</link>
1035
-
are available for return type declarations as are available for argument
1036
-
type declarations.
1037
-
</para>
684
+
<example>
685
+
<title>Combining named arguments with positional arguments</title>
686
+
<programlisting role="php">
687
+
<![CDATA[
688
+
<?php
689
+
htmlspecialchars($string, double_encode: false);
690
+
// Same as
691
+
htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8', false);
692
+
?>
693
+
]]>
694
+
</programlisting>
695
+
</example>
1038
696

1039
-
<para>
1040
-
<link linkend="functions.arguments.type-declaration.strict">Strict typing</link>
1041
-
also has an effect on return type declarations. In the default weak mode,
1042
-
returned values will be coerced to the correct type if they are not
1043
-
already of that type. In strong mode, the returned value must be of the
1044
-
correct type, otherwise a <classname>TypeError</classname> will be thrown.
1045
-
</para>
697
+
<para>
698
+
Passing the same parameter multiple times results in an Error exception.
699
+
</para>
1046
700

1047
-
<para>
1048
-
As of PHP 7.1.0, return values can be marked as nullable by prefixing the
1049
-
type name with a question mark (<literal>?</literal>). This signifies that
1050
-
the function returns either the specified type or &null;.
1051
-
</para>
701
+
<example>
702
+
<title>Error thrown when passing the same parameter multiple times</title>
703
+
<programlisting role="php">
704
+
<![CDATA[
705
+
<?php
706
+
function foo($param) { ... }
707
+

708
+
foo(param: 1, param: 2);
709
+
// Error: Named parameter $param overwrites previous argument
710
+
foo(1, param: 2);
711
+
// Error: Named parameter $param overwrites previous argument
712
+
?>
713
+
]]>
714
+
</programlisting>
715
+
</example>
1052
716

1053
-
<note>
1054
717
<para>
1055
-
When overriding a parent method, the child's method must match any return
1056
-
type declaration on the parent. If the parent doesn't define a return
1057
-
type, then the child method may do so.
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.
1058
720
</para>
1059
-
</note>
1060
-

1061
-
<sect3 xml:id="functions.returning-values.type-declaration.examples">
1062
-
&reftitle.examples;
1063
721

1064
722
<example>
1065
-
<title>Basic return type declaration</title>
723
+
<title>Use named arguments after unpacking</title>
1066
724
<programlisting role="php">
1067
725
<![CDATA[
1068
726
<?php
1069
-
function sum($a, $b): float {
1070
-
return $a + $b;
727
+
function foo($a, $b, $c = 3, $d = 4) {
728
+
return $a + $b + $c + $d;
1071
729
}
1072
730

1073
-
// Note that a float will be returned.
1074
-
var_dump(sum(1, 2));
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
1075
735
?>
1076
736
]]>
1077
-
</programlisting>
1078
-
&example.outputs;
1079
-
<screen>
1080
-
<![CDATA[
1081
-
float(3)
1082
-
]]>
1083
-
</screen>
1084
-
</example>
737
+
</programlisting>
738
+
</example>
739
+

740
+
</sect2>
741
+
</sect1>
742
+
743
+
<sect1 xml:id="functions.returning-values">
744
+
<title>Returning values</title>
745
+
746
+
<para>
747
+
Values are returned by using the optional return statement. Any
748
+
type may be returned, including arrays and objects. This causes the
749
+
function to end its execution immediately and pass control back to
750
+
the line from which it was called. See <function>return</function>
751
+
for more information.
752
+
</para>
753
+

754
+
<note>
755
+
<para>
756
+
If the <function>return</function> is omitted the value &null; will be
757
+
returned.
758
+
</para>
759
+
</note>
1085
760

761
+
<sect2>
762
+
<title>Use of return</title>
763
+
<para>
1086
764
<example>
1087
-
<title>Strict mode in action</title>
765
+
<title>Use of <function>return</function></title>
1088
766
<programlisting role="php">
1089
767
<![CDATA[
1090
768
<?php
1091
-
declare(strict_types=1);
1092
-

1093
-
function sum($a, $b): int {
1094
-
return $a + $b;
769
+
function square($num)
770
+
{
771
+
return $num * $num;
1095
772
}
1096
-

1097
-
var_dump(sum(1, 2));
1098
-
var_dump(sum(1, 2.5));
773
+
echo square(4); // outputs '16'.
1099
774
?>
1100
775
]]>
1101
776
</programlisting>
1102
-
&example.outputs;
1103
-
<screen>
1104
-
<![CDATA[
1105
-
int(3)
1106
-

1107
-
Fatal error: Uncaught TypeError: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5
1108
-
Stack trace:
1109
-
#0 -(9): sum(1, 2.5)
1110
-
#1 {main}
1111
-
thrown in - on line 5
1112
-
]]>
1113
-
</screen>
1114
777
</example>
778
+
</para>
1115
779

780
+
<para>
781
+
A function can not return multiple values, but similar results can be
782
+
obtained by returning an array.
783
+
</para>
784
+
<para>
1116
785
<example>
1117
-
<title>Returning an object</title>
786
+
<title>Returning an array to get multiple values</title>
1118
787
<programlisting role="php">
1119
788
<![CDATA[
1120
789
<?php
1121
-
class C {}
1122
-

1123
-
function getC(): C {
1124
-
return new C;
790
+
function small_numbers()
791
+
{
792
+
return [0, 1, 2];
1125
793
}
794
+
// Array destructuring will collect each member of the array individually
795
+
[$zero, $one, $two] = small_numbers();
796
+

797
+
// Prior to 7.1.0, the only equivalent alternative is using list() construct
798
+
list($zero, $one, $two) = small_numbers();
1126
799

1127
-
var_dump(getC());
1128
800
?>
1129
801
]]>
1130
802
</programlisting>
1131
-
&example.outputs;
1132
-
<screen>
1133
-
<![CDATA[
1134
-
object(C)#1 (0) {
1135
-
}
1136
-
]]>
1137
-
</screen>
1138
803
</example>
1139
-

804
+
</para>
805
+
<para>
806
+
To return a reference from a function, use the reference operator &amp; in
807
+
both the function declaration and when assigning the returned value to a
808
+
variable:
809
+
</para>
810
+
<para>
1140
811
<example>
1141
-
<title>Nullable return type declaration (as of PHP 7.1.0)</title>
812
+
<title>Returning a reference from a function</title>
1142
813
<programlisting role="php">
1143
814
<![CDATA[
1144
815
<?php
1145
-
function get_item(): ?string {
1146
-
if (isset($_GET['item'])) {
1147
-
return $_GET['item'];
1148
-
} else {
1149
-
return null;
1150
-
}
816
+
function &returns_reference()
817
+
{
818
+
return $someref;
1151
819
}
820
+

821
+
$newref =& returns_reference();
1152
822
?>
1153
823
]]>
1154
824
</programlisting>
1155
825
</example>
1156
-
</sect3>
826
+
</para>
827
+
<simpara>
828
+
For more information on references, please check out <link
829
+
linkend="language.references">References Explained</link>.
830
+
</simpara>
1157
831
</sect2>
1158
832
</sect1>
1159
833

...
...
@@ -1265,7 +939,6 @@ Foo::$variable(); // This calls $foo->Variable() reading $variable in this scop
1265
939
</example>
1266
940
</para>
1267
941
<para>
1268
-
As of PHP 5.4.0, you can call any <type>callable</type> stored in a variable.
1269
942
<example>
1270
943
<title>Complex callables</title>
1271
944
<programlisting role="php">
...
...
@@ -1288,46 +961,22 @@ $func(); // prints "bar"
1288
961
$func = array(new Foo, "baz");
1289
962
$func(); // prints "baz"
1290
963
$func = "Foo::bar";
1291
-
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
964
+
$func(); // prints "bar"
1292
965
?>
1293
966
]]>
1294
967
</programlisting>
1295
968
</example>
1296
969
</para>
1297
970

1298
-
<para>
1299
-
See also <function>is_callable</function>, <function>call_user_func</function>,
1300
-
<link linkend="language.variables.variable">
1301
-
variable variables</link> and <function>function_exists</function>.
1302
-
</para>
1303
-
1304
-
<sect2 role="changelog">
1305
-
&reftitle.changelog;
971
+
<sect2 role="seealso">
972
+
&reftitle.seealso;
1306
973
<para>
1307
-
<informaltable>
1308
-
<tgroup cols="2">
1309
-
<thead>
1310
-
<row>
1311
-
<entry>&Version;</entry>
1312
-
<entry>&Description;</entry>
1313
-
</row>
1314
-
</thead>
1315
-
<tbody>
1316
-
<row>
1317
-
<entry>7.0.0</entry>
1318
-
<entry>
1319
-
'ClassName::methodName' is allowed as variable function.
1320
-
</entry>
1321
-
</row>
1322
-
<row>
1323
-
<entry>5.4.0</entry>
1324
-
<entry>
1325
-
Arrays, which are valid callables, are allowed as variable functions.
1326
-
</entry>
1327
-
</row>
1328
-
</tbody>
1329
-
</tgroup>
1330
-
</informaltable>
974
+
<simplelist>
975
+
<member><function>is_callable</function></member>
976
+
<member><function>call_user_func</function></member>
977
+
<member><function>function_exists</function></member>
978
+
<member><link linkend="language.variables.variable">variable variables</link></member>
979
+
</simplelist>
1331
980
</para>
1332
981
</sect2>
1333
982
</sect1>
...
...
@@ -1375,14 +1024,54 @@ $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
1375
1024
the return value of the function is undefined. In this case it will
1376
1025
likely return &null; but this is just a convention, and cannot be relied
1377
1026
upon.
1027
+
As of PHP 8.0.0, a <classname>TypeError</classname> exception is supposed to
1028
+
be thrown in this case.
1378
1029
</simpara>
1379
1030
</note>
1380
-
<para>
1381
-
See also <function>function_exists</function>,
1382
-
<link linkend="funcref">the function reference</link>,
1383
-
<function>get_extension_funcs</function>, and
1384
-
<function>dl</function>.
1385
-
</para>
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>
1063
+

1064
+
<sect2 role="seealso">
1065
+
&reftitle.seealso;
1066
+
<para>
1067
+
<simplelist>
1068
+
<member><function>function_exists</function></member>
1069
+
<member><link linkend="funcref">the function reference</link></member>
1070
+
<member><function>get_extension_funcs</function></member>
1071
+
<member><function>dl</function></member>
1072
+
</simplelist>
1073
+
</para>
1074
+
</sect2>
1386
1075
</sect1>
1387
1076
1388
1077
<sect1 xml:id="functions.anonymous">
...
...
@@ -1391,7 +1080,7 @@ $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
1391
1080
<simpara>
1392
1081
Anonymous functions, also known as <literal>closures</literal>, allow the
1393
1082
creation of functions which have no specified name. They are most useful as
1394
-
the value of <link linkend="language.types.callback">callback</link>
1083
+
the value of <type>callable</type>
1395
1084
parameters, but they have many other uses.
1396
1085
</simpara>
1397
1086
<simpara>
...
...
@@ -1426,8 +1115,7 @@ echo preg_replace_callback('~-([a-z])~', function ($match) {
1426
1115
<programlisting role="php">
1427
1116
<![CDATA[
1428
1117
<?php
1429
-
$greet = function($name)
1430
-
{
1118
+
$greet = function($name) {
1431
1119
printf("Hello %s\r\n", $name);
1432
1120
};
1433
1121

...
...
@@ -1441,8 +1129,10 @@ $greet('PHP');
1441
1129
<simpara>
1442
1130
Closures may also inherit variables from the parent scope. Any such
1443
1131
variables must be passed to the <literal>use</literal> language construct.
1444
-
From PHP 7.1, these variables must not include &link.superglobals;,
1132
+
As of PHP 7.1, these variables must not include &link.superglobals;,
1445
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.
1446
1136
</simpara>
1447
1137

1448
1138
<example>
...
...
@@ -1488,6 +1178,12 @@ $example = function ($arg) use ($message) {
1488
1178
var_dump($arg . ' ' . $message);
1489
1179
};
1490
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());
1491
1187
?>
1492
1188
]]>
1493
1189
</programlisting>
...
...
@@ -1501,10 +1197,15 @@ string(5) "hello"
1501
1197
string(5) "hello"
1502
1198
string(5) "world"
1503
1199
string(11) "hello world"
1200
+
string(11) "hello world"
1504
1201
]]>
1505
1202
</screen>
1506
1203
</example>
1507
1204

1205
+
<para>
1206
+
As of PHP 8.0.0, the list of scope-inherited variables may include a trailing
1207
+
comma, which will be ignored.
1208
+
</para>
1508
1209
<simpara>
1509
1210
Inheriting variables from the parent scope is <emphasis>not</emphasis>
1510
1211
the same as using global variables.
...
...
@@ -1604,16 +1305,10 @@ object(Test)#1 (0) {
1604
1305
}
1605
1306
]]>
1606
1307
</screen>
1607
-
&example.outputs.53;
1608
-
<screen>
1609
-
<![CDATA[
1610
-
Notice: Undefined variable: this in script.php on line 8
1611
-
NULL]]>
1612
-
</screen>
1613
1308
</example>
1614
1309

1615
1310
<para>
1616
-
As of PHP 5.4.0, when declared in the context of a class, the current class is
1311
+
When declared in the context of a class, the current class is
1617
1312
automatically bound to it, making <literal>$this</literal> available
1618
1313
inside of the function's scope. If this automatic binding of the current
1619
1314
class is not wanted, then
...
...
@@ -1624,7 +1319,7 @@ NULL]]>
1624
1319
<sect2 xml:id="functions.anonymous-functions.static">
1625
1320
<title>Static anonymous functions</title>
1626
1321
<para>
1627
-
As of PHP 5.4, anonymous functions may be declared statically. This
1322
+
Anonymous functions may be declared statically. This
1628
1323
prevents them from having the current class automatically bound to
1629
1324
them. Objects may also not be bound to them at runtime.
1630
1325
</para>
...
...
@@ -1670,7 +1365,7 @@ NULL
1670
1365
$func = static function() {
1671
1366
// function body
1672
1367
};
1673
-
$func = $func->bindTo(new StdClass);
1368
+
$func = $func->bindTo(new stdClass);
1674
1369
$func();
1675
1370

1676
1371
?>
...
...
@@ -1706,17 +1401,169 @@ Warning: Cannot bind an instance to a static closure in %s on line %d
1706
1401
parameter.
1707
1402
</entry>
1708
1403
</row>
1404
+
</tbody>
1405
+
</tgroup>
1406
+
</informaltable>
1407
+
</para>
1408
+
</sect2>
1409
+

1410
+
<sect2 role="notes">
1411
+
&reftitle.notes;
1412
+
<note>
1413
+
<simpara>
1414
+
It is possible to use <function>func_num_args</function>,
1415
+
<function>func_get_arg</function>, and <function>func_get_args</function>
1416
+
from within a closure.
1417
+
</simpara>
1418
+
</note>
1419
+
</sect2>
1420
+

1421
+
</sect1>
1422
+
<sect1 xml:id="functions.arrow">
1423
+
<title>Arrow Functions</title>
1424
+

1425
+
<simpara>
1426
+
Arrow functions were introduced in PHP 7.4 as a more concise syntax for
1427
+
<link linkend="functions.anonymous">anonymous functions</link>.
1428
+
</simpara>
1429
+
<simpara>
1430
+
Both anonymous functions and arrow functions are implemented using the
1431
+
<link linkend="class.closure"><classname>Closure</classname></link> class.
1432
+
</simpara>
1433
+

1434
+
<simpara>
1435
+
Arrow functions have the basic form
1436
+
<code>fn (argument_list) =&gt; expr</code>.
1437
+
</simpara>
1438
+

1439
+
<simpara>
1440
+
Arrow functions support the same features as
1441
+
<link linkend="functions.anonymous">anonymous functions</link>,
1442
+
except that using variables from the parent scope is always automatic.
1443
+
</simpara>
1444
+

1445
+
<simpara>
1446
+
When a variable used in the expression is defined in the parent scope
1447
+
it will be implicitly captured by-value.
1448
+
In the following example, the functions <varname>$fn1</varname> and
1449
+
<varname>$fn2</varname> behave the same way.
1450
+
</simpara>
1451
+

1452
+
<para>
1453
+
<example>
1454
+
<title>Arrow functions capture variables by value automatically</title>
1455
+
<programlisting role="php">
1456
+
<![CDATA[
1457
+
<?php
1458
+

1459
+
$y = 1;
1460
+
1461
+
$fn1 = fn($x) => $x + $y;
1462
+
// equivalent to using $y by value:
1463
+
$fn2 = function ($x) use ($y) {
1464
+
return $x + $y;
1465
+
};
1466
+

1467
+
var_export($fn1(3));
1468
+
?>
1469
+
]]>
1470
+
</programlisting>
1471
+
&example.outputs;
1472
+
<screen>
1473
+
<![CDATA[
1474
+
4
1475
+
]]>
1476
+
</screen>
1477
+
</example>
1478
+
</para>
1479
+
<simpara>
1480
+
This also works if the arrow functions are nested:
1481
+
</simpara>
1482
+
<para>
1483
+
<example>
1484
+
<title>Arrow functions capture variables by value automatically, even when nested</title>
1485
+
<programlisting role="php">
1486
+
<![CDATA[
1487
+
<?php
1488
+

1489
+
$z = 1;
1490
+
$fn = fn($x) => fn($y) => $x * $y + $z;
1491
+
// Outputs 51
1492
+
var_export($fn(5)(10));
1493
+
?>
1494
+
]]>
1495
+
</programlisting>
1496
+
</example>
1497
+
</para>
1498
+
<simpara>
1499
+
Similarly to anonymous functions,
1500
+
the arrow function syntax allows arbitrary function signatures,
1501
+
including parameter and return types, default values, variadics,
1502
+
as well as by-reference passing and returning.
1503
+
All of the following are valid examples of arrow functions:
1504
+
</simpara>
1505
+
<para>
1506
+
<example>
1507
+
<title>Examples of arrow functions</title>
1508
+
<programlisting role="php">
1509
+
<![CDATA[
1510
+
<?php
1511
+

1512
+
fn(array $x) => $x;
1513
+
static fn(): int => $x;
1514
+
fn($x = 42) => $x;
1515
+
fn(&$x) => $x;
1516
+
fn&($x) => $x;
1517
+
fn($x, ...$rest) => $rest;
1518
+

1519
+
?>
1520
+
]]>
1521
+
</programlisting>
1522
+
</example>
1523
+
</para>
1524
+
<simpara>
1525
+
Arrow functions use by-value variable binding.
1526
+
This is roughly equivalent to performing a <code>use($x)</code> for every
1527
+
variable <varname>$x</varname> used inside the arrow function.
1528
+
A by-value binding means that it is not possible to modify any values
1529
+
from the outer scope.
1530
+
<link linkend="functions.anonymous">Anonymous functions</link>
1531
+
can be used instead for by-ref bindings.
1532
+
</simpara>
1533
+
<para>
1534
+
<example>
1535
+
<title>Values from the outer scope cannot be modified by arrow functions</title>
1536
+
<programlisting role="php">
1537
+
<![CDATA[
1538
+
<?php
1539
+

1540
+
$x = 1;
1541
+
$fn = fn() => $x++; // Has no effect
1542
+
$fn();
1543
+
var_export($x); // Outputs 1
1544
+

1545
+
?>
1546
+
]]>
1547
+
</programlisting>
1548
+
</example>
1549
+
</para>
1550
+
1551
+
<sect2 role="changelog">
1552
+
&reftitle.changelog;
1553
+
<para>
1554
+
<informaltable>
1555
+
<tgroup cols="2">
1556
+
<thead>
1709
1557
<row>
1710
-
<entry>5.4.0</entry>
1711
-
<entry>
1712
-
Anonymous functions may use <varname>$this</varname>, as well as be
1713
-
declared statically.
1714
-
</entry>
1558
+
<entry>&Version;</entry>
1559
+
<entry>&Description;</entry>
1715
1560
</row>
1561
+
</thead>
1562
+
<tbody>
1716
1563
<row>
1717
-
<entry>5.3.0</entry>
1564
+
<entry>7.4.0</entry>
1718
1565
<entry>
1719
-
Anonymous functions become available.
1566
+
Arrow functions became available.
1720
1567
</entry>
1721
1568
</row>
1722
1569
</tbody>
...
...
@@ -1731,11 +1578,131 @@ Warning: Cannot bind an instance to a static closure in %s on line %d
1731
1578
<simpara>
1732
1579
It is possible to use <function>func_num_args</function>,
1733
1580
<function>func_get_arg</function>, and <function>func_get_args</function>
1734
-
from within a closure.
1581
+
from within an arrow function.
1735
1582
</simpara>
1736
1583
</note>
1737
1584
</sect2>
1585
+
</sect1>
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>
1738
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>
1739
1706
</sect1>
1740
1707

1741
1708
</chapter>
1742
1709