language/functions.xml
f94d903985119d3ac00f4528551df947f57b667f
...
...
@@ -28,7 +28,7 @@ function foo($arg_1, $arg_2, /* ..., */ $arg_n)
28
28
29
29
<simpara>
30
30
Any valid PHP code may appear inside a function, even other
31
-
functions and <link linkend="keyword.class">class</link>
31
+
functions and <link linkend="language.oop5.basic.class">class</link>
32
32
definitions.
33
33
</simpara>
34
34
<para>
...
...
@@ -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
-
<literal>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*</literal>.
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,427 +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
370
-
certain type at call time. 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><type>array</type></entry>
404
-
<entry>
405
-
The parameter must be an <type>array</type>.
406
-
</entry>
407
-
<entry>PHP 5.1.0</entry>
408
-
</row>
409
-
<row>
410
-
<entry><type>callable</type></entry>
411
-
<entry>
412
-
The parameter must be a valid <type>callable</type>.
413
-
</entry>
414
-
<entry>PHP 5.4.0</entry>
415
-
</row>
416
-
<row>
417
-
<entry><type>bool</type></entry>
418
-
<entry>
419
-
The parameter must be a <type>boolean</type> value.
420
-
</entry>
421
-
<entry>PHP 7.0.0</entry>
422
-
</row>
423
-
<row>
424
-
<entry><type>float</type></entry>
425
-
<entry>
426
-
The parameter must be a <type>float</type>ing point number.
427
-
</entry>
428
-
<entry>PHP 7.0.0</entry>
429
-
</row>
430
-
<row>
431
-
<entry><type>int</type></entry>
432
-
<entry>
433
-
The parameter must be an <type>integer</type>.
434
-
</entry>
435
-
<entry>PHP 7.0.0</entry>
436
-
</row>
437
-
<row>
438
-
<entry><type>string</type></entry>
439
-
<entry>
440
-
The parameter must be a <type>string</type>.
441
-
</entry>
442
-
<entry>PHP 7.0.0</entry>
443
-
</row>
444
-
</tbody>
445
-
</tgroup>
446
-
</informaltable>
447
-
</sect3>
448
-

449
-
<sect3 xml:id="functions.arguments.type-declaration.examples">
450
-
&reftitle.examples;
451
-
<example>
452
-
<title>Basic class type declaration</title>
453
-
<programlisting role="php">
454
-
<![CDATA[
455
-
<?php
456
-
class C {}
457
-
class D extends C {}
458
-

459
-
// This doesn't extend C.
460
-
class E {}
461
-

462
-
function f(C $c) {
463
-
echo get_class($c)."\n";
464
-
}
465
-

466
-
f(new C);
467
-
f(new D);
468
-
f(new E);
469
-
?>
470
-
]]>
471
-
</programlisting>
472
-
&example.outputs;
473
-
<screen>
474
-
<![CDATA[
475
-
C
476
-
D
477
-

478
-
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
479
-
Stack trace:
480
-
#0 -(14): f(Object(E))
481
-
#1 {main}
482
-
thrown in - on line 8
483
-
]]>
484
-
</screen>
485
-
</example>
486
-

487
-
<example>
488
-
<title>Basic interface type declaration</title>
489
-
<programlisting role="php">
490
-
<![CDATA[
491
-
<?php
492
-
interface I { public function f(); }
493
-
class C implements I { public function f() {} }
494
-

495
-
// This doesn't implement I.
496
-
class E {}
497
-

498
-
function f(I $i) {
499
-
echo get_class($i)."\n";
500
-
}
501
-

502
-
f(new C);
503
-
f(new E);
504
-
?>
505
-
]]>
506
-
</programlisting>
507
-
&example.outputs;
508
-
<screen>
509
-
<![CDATA[
510
-
C
511
-

512
-
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
513
-
Stack trace:
514
-
#0 -(13): f(Object(E))
515
-
#1 {main}
516
-
thrown in - on line 8
517
-
]]>
518
-
</screen>
519
-
</example>
520
-

521
375
<example>
522
-
<title>Nullable type declaration</title>
376
+
<title>Incorrect usage of default function arguments</title>
523
377
<programlisting role="php">
524
378
<![CDATA[
525
379
<?php
526
-
class C {}
527
-

528
-
function f(C $c = null) {
529
-
var_dump($c);
380
+
function makeyogurt($container = "bowl", $flavour)
381
+
{
382
+
return "Making a $container of $flavour yogurt.\n";
530
383
}
531
384
532
-
f(new C);
533
-
f(null);
385
+
echo makeyogurt("raspberry"); // "raspberry" is $container, not $flavour
534
386
?>
535
387
]]>
536
388
</programlisting>
537
389
&example.outputs;
538
390
<screen>
539
391
<![CDATA[
540
-
object(C)#1 (0) {
541
-
}
542
-
NULL
392
+
Fatal error: Uncaught ArgumentCountError: Too few arguments
393
+
to function makeyogurt(), 1 passed in example.php on line 42
543
394
]]>
544
395
</screen>
545
396
</example>
546
-
</sect3>
547
-

548
-
<sect3 xml:id="functions.arguments.type-declaration.strict">
549
-
<title>Strict typing</title>
550
-

551
-
<para>
552
-
By default, PHP will coerce values of the wrong type into the expected
553
-
scalar type if possible. For example, a function that is given an
554
-
<type>integer</type> for a parameter that expects a <type>string</type>
555
-
will get a variable of type <type>string</type>.
556
-
</para>
557
-

558
-
<para>
559
-
It is possible to enable strict mode on a per-file basis. In strict
560
-
mode, only a variable of exact type of the type declaration will be
561
-
accepted, or a <classname>TypeError</classname> will be thrown. The
562
-
only exception to this rule is that an <type>integer</type> may be given
563
-
to a function expecting a <type>float</type>.
564
-
</para>
565
-

566
-
<para>
567
-
To enable strict mode, the &declare; statement is used with the
568
-
<literal>strict_types</literal> declaration:
569
-
</para>
570
-

571
-
<caution>
572
-
<para>
573
-
Enabling strict mode will also affect
574
-
<link linkend="functions.returning-values.type-declaration">return type declarations</link>.
575
-
</para>
576
-
</caution>
577
-

578
-
<note>
579
-
<para>
580
-
Strict typing applies to function calls made from
581
-
<emphasis>within</emphasis> the file with strict typing enabled, not to
582
-
the functions declared within that file. If a file without strict
583
-
typing enabled makes a call to a function that was defined in a file
584
-
with strict typing, the caller's preference (weak typing) will be
585
-
respected, and the value will be coerced.
586
-
</para>
587
-
</note>
588
-

589
-
<note>
590
-
<para>
591
-
Strict typing is only defined for scalar type declarations, and as
592
-
such, requires PHP 7.0.0 or later, as scalar type declarations were
593
-
added in that version.
594
-
</para>
595
-
</note>
596
-

397
+
</para>
398
+
<para>
399
+
Now, compare the above with this:
400
+
</para>
401
+
<para>
597
402
<example>
598
-
<title>Strict typing</title>
403
+
<title>Correct usage of default function arguments</title>
599
404
<programlisting role="php">
600
405
<![CDATA[
601
406
<?php
602
-
declare(strict_types=1);
603
-

604
-
function sum(int $a, int $b) {
605
-
return $a + $b;
407
+
function makeyogurt($flavour, $container = "bowl")
408
+
{
409
+
return "Making a $container of $flavour yogurt.\n";
606
410
}
607
411
608
-
var_dump(sum(1, 2));
609
-
var_dump(sum(1.5, 2.5));
412
+
echo makeyogurt("raspberry"); // "raspberry" is $flavour
610
413
?>
611
414
]]>
612
415
</programlisting>
613
416
&example.outputs;
614
417
<screen>
615
418
<![CDATA[
616
-
int(3)
617
-

618
-
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
619
-
Stack trace:
620
-
#0 -(9): sum(1.5, 2.5)
621
-
#1 {main}
622
-
thrown in - on line 4
419
+
Making a bowl of raspberry yogurt.
623
420
]]>
624
421
</screen>
625
422
</example>
626
-

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>
627
429
<example>
628
-
<title>Weak typing</title>
430
+
<title>Correct usage of default function arguments</title>
629
431
<programlisting role="php">
630
432
<![CDATA[
631
433
<?php
632
-
function sum(int $a, int $b) {
633
-
return $a + $b;
434
+
function makeyogurt($container = "bowl", $flavour = "raspberry", $style = "Greek")
435
+
{
436
+
return "Making a $container of $flavour $style yogurt.\n";
634
437
}
635
438

636
-
var_dump(sum(1, 2));
637
-

638
-
// These will be coerced to integers: note the output below!
639
-
var_dump(sum(1.5, 2.5));
439
+
echo makeyogurt(style: "natural");
640
440
?>
641
441
]]>
642
442
</programlisting>
643
443
&example.outputs;
644
444
<screen>
645
445
<![CDATA[
646
-
int(3)
647
-
int(3)
446
+
Making a bowl of raspberry natural yogurt.
648
447
]]>
649
448
</screen>
650
449
</example>
651
-

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.
652
459
<example>
653
-
<title>Catching <classname>TypeError</classname></title>
460
+
<title>Declaring optional arguments after mandatory arguments</title>
654
461
<programlisting role="php">
655
462
<![CDATA[
656
-
<?php
657
-
declare(strict_types=1);
658
-

659
-
function sum(int $a, int $b) {
660
-
return $a + $b;
661
-
}
662
-

663
-
try {
664
-
var_dump(sum(1, 2));
665
-
var_dump(sum(1.5, 2.5));
666
-
} catch (TypeError $e) {
667
-
echo 'Error: '.$e->getMessage();
668
-
}
669
-
?>
670
-
]]>
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
+
]]>
671
471
</programlisting>
672
-
&example.outputs;
673
-
<screen>
674
-
<![CDATA[
675
-
int(3)
676
-
Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10
677
-
]]>
678
-
</screen>
679
472
</example>
680
-
</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>
681
486
</sect2>
487
+

682
488
<sect2 xml:id="functions.variable-arg-list">
683
489
<title>Variable-length argument lists</title>
684
490

685
491
<simpara>
686
492
PHP has support for variable-length argument lists in
687
-
user-defined functions. This is implemented using the
688
-
<literal>...</literal> token in PHP 5.6 and later, and using the
689
-
<function>func_num_args</function>,
690
-
<function>func_get_arg</function>, and
691
-
<function>func_get_args</function> functions in PHP 5.5 and earlier.
493
+
user-defined functions by using the
494
+
<literal>...</literal> token.
692
495
</simpara>
693
496

694
-
<sect3 xml:id="functions.variable-arg-list.new">
695
-
<title><literal>...</literal> in PHP 5.6+</title>
696
-

697
-
<para>
698
-
In PHP 5.6 and later, argument lists may include the
699
-
<literal>...</literal> token to denote that the function accepts a
700
-
variable number of arguments. The arguments will be passed into the
701
-
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;:
702
502

703
-
<example>
704
-
<title>Using <literal>...</literal> to access variable arguments</title>
705
-
<programlisting role="php">
503
+
<example>
504
+
<title>Using <literal>...</literal> to access variable arguments</title>
505
+
<programlisting role="php">
706
506
<![CDATA[
707
507
<?php
708
508
function sum(...$numbers) {
...
...
@@ -716,24 +516,24 @@ function sum(...$numbers) {
716
516
echo sum(1, 2, 3, 4);
717
517
?>
718
518
]]>
719
-
</programlisting>
720
-
&example.outputs;
721
-
<screen>
519
+
</programlisting>
520
+
&example.outputs;
521
+
<screen>
722
522
<![CDATA[
723
523
10
724
524
]]>
725
-
</screen>
726
-
</example>
727
-
</para>
728
-

729
-
<para>
730
-
You can also use <literal>...</literal> when calling functions to unpack
731
-
an <type>array</type> or <classname>Traversable</classname> variable or
732
-
literal into the argument list:
733
-

734
-
<example>
735
-
<title>Using <literal>...</literal> to provide arguments</title>
736
-
<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">
737
537
<![CDATA[
738
538
<?php
739
539
function add($a, $b) {
...
...
@@ -746,33 +546,33 @@ $a = [1, 2];
746
546
echo add(...$a);
747
547
?>
748
548
]]>
749
-
</programlisting>
750
-
&example.outputs;
751
-
<screen>
549
+
</programlisting>
550
+
&example.outputs;
551
+
<screen>
752
552
<![CDATA[
753
553
3
754
554
3
755
555
]]>
756
-
</screen>
757
-
</example>
758
-
</para>
759
-

760
-
<para>
761
-
You may specify normal positional arguments before the
762
-
<literal>...</literal> token. In this case, only the trailing arguments
763
-
that don't match a positional argument will be added to the array
764
-
generated by <literal>...</literal>.
765
-
</para>
766
-

767
-
<para>
768
-
It is also possible to add a
769
-
<link linkend="language.oop5.typehinting">type hint</link> before the
770
-
<literal>...</literal> token. If this is present, then all arguments
771
-
captured by <literal>...</literal> must be objects of the hinted class.
772
-

773
-
<example>
774
-
<title>Type hinted variable arguments</title>
775
-
<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">
776
576
<![CDATA[
777
577
<?php
778
578
function total_intervals($unit, DateInterval ...$intervals) {
...
...
@@ -791,262 +591,243 @@ echo total_intervals('d', $a, $b).' days';
791
591
echo total_intervals('d', null);
792
592
?>
793
593
]]>
794
-
</programlisting>
795
-
&example.outputs;
796
-
<screen>
594
+
</programlisting>
595
+
&example.outputs;
596
+
<screen>
797
597
<![CDATA[
798
598
3 days
799
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
800
600
]]>
801
-
</screen>
802
-
</example>
803
-
</para>
804
-

805
-
<para>
806
-
Finally, you may also pass variable arguments
807
-
<link linkend="functions.arguments.by-reference">by reference</link> by
808
-
prefixing the <literal>...</literal> with an ampersand
809
-
(<literal>&amp;</literal>).
810
-
</para>
811
-
</sect3>
812
-

813
-
<sect3 xml:id="functions.variable-arg-list.old">
814
-
<title>Older versions of PHP</title>
815
-

816
-
<para>
817
-
No special syntax is required to note that a function is variadic;
818
-
however access to the function's arguments must use
819
-
<function>func_num_args</function>, <function>func_get_arg</function>
820
-
and <function>func_get_args</function>.
821
-
</para>
822
-

823
-
<para>
824
-
The first example above would be implemented as follows in PHP 5.5 and
825
-
earlier:
826
-

827
-
<example>
828
-
<title>Accessing variable arguments in PHP 5.5 and earlier</title>
829
-
<programlisting role="php">
830
-
<![CDATA[
831
-
<?php
832
-
function sum() {
833
-
$acc = 0;
834
-
foreach (func_get_args() as $n) {
835
-
$acc += $n;
836
-
}
837
-
return $acc;
838
-
}
601
+
</screen>
602
+
</example>
603
+
</para>
839
604

840
-
echo sum(1, 2, 3, 4);
841
-
?>
842
-
]]>
843
-
</programlisting>
844
-
&example.outputs;
845
-
<screen>
846
-
<![CDATA[
847
-
10
848
-
]]>
849
-
</screen>
850
-
</example>
851
-
</para>
852
-
</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>
853
611

854
612
</sect2>
855
-
</sect1>
856
-
857
-
<sect1 xml:id="functions.returning-values">
858
-
<title>Returning values</title>
859
613

860
-
<para>
861
-
Values are returned by using the optional return statement. Any
862
-
type may be returned, including arrays and objects. This causes the
863
-
function to end its execution immediately and pass control back to
864
-
the line from which it was called. See <function>return</function>
865
-
for more information.
866
-
</para>
614
+
<sect2 xml:id="functions.named-arguments">
615
+
<title>Named Arguments</title>
867
616

868
-
<note>
869
617
<para>
870
-
If the <function>return</function> is omitted the value &null; will be
871
-
returned.
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>
624
+

625
+
<para>
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.
872
630
</para>
873
-
</note>
874
631

875
-
<sect2>
876
-
<title>Use of return</title>
877
-
<para>
878
632
<example>
879
-
<title>Use of <function>return</function></title>
633
+
<title>Named argument syntax</title>
880
634
<programlisting role="php">
881
635
<![CDATA[
882
636
<?php
883
-
function square($num)
884
-
{
885
-
return $num * $num;
886
-
}
887
-
echo square(4); // outputs '16'.
637
+
myFunction(paramName: $value);
638
+
array_foobar(array: $value);
639
+

640
+
// NOT supported.
641
+
function_name($variableStoringParamName: $value);
888
642
?>
889
643
]]>
890
644
</programlisting>
891
645
</example>
892
-
</para>
893
646

894
-
<para>
895
-
A function can not return multiple values, but similar results can be
896
-
obtained by returning an array.
897
-
</para>
898
-
<para>
899
647
<example>
900
-
<title>Returning an array to get multiple values</title>
648
+
<title>Positional arguments versus named arguments</title>
901
649
<programlisting role="php">
902
650
<![CDATA[
903
651
<?php
904
-
function small_numbers()
905
-
{
906
-
return array (0, 1, 2);
907
-
}
908
-
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);
909
657
?>
910
658
]]>
911
659
</programlisting>
912
660
</example>
913
-
</para>
914
-
<para>
915
-
To return a reference from a function, use the reference operator &amp; in
916
-
both the function declaration and when assigning the returned value to a
917
-
variable:
918
-
</para>
919
-
<para>
661
+

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

920
666
<example>
921
-
<title>Returning a reference from a function</title>
667
+
<title>Same example as above with a different order of parameters</title>
922
668
<programlisting role="php">
923
669
<![CDATA[
924
670
<?php
925
-
function &returns_reference()
926
-
{
927
-
return $someref;
671
+
array_fill(value: 50, count: 100, start_index: 0);
672
+
?>
673
+
]]>
674
+
</programlisting>
675
+
</example>
676
+

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>
683
+

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>
696
+

697
+
<para>
698
+
Passing the same parameter multiple times results in an Error exception.
699
+
</para>
700
+

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>
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;
928
729
}
929
730

930
-
$newref =& returns_reference();
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
931
735
?>
932
736
]]>
933
737
</programlisting>
934
738
</example>
935
-
</para>
936
-
<simpara>
937
-
For more information on references, please check out <link
938
-
linkend="language.references">References Explained</link>.
939
-
</simpara>
940
-
</sect2>
941
739

942
-
<sect2 xml:id="functions.returning-values.type-declaration">
943
-
<title>Return type declarations</title>
740
+
</sect2>
741
+
</sect1>
944
742
945
-
<para>
946
-
PHP 7 adds support for return type declarations. Similarly to
947
-
<link linkend="functions.arguments.type-declaration">argument type declarations</link>,
948
-
return type declarations specify the type of the value that will be
949
-
returned from a function. The same
950
-
<link linkend="functions.arguments.type-declaration.types">types</link>
951
-
are available for return type declarations as are available for argument
952
-
type declarations.
953
-
</para>
743
+
<sect1 xml:id="functions.returning-values">
744
+
<title>Returning values</title>
954
745
955
746
<para>
956
-
<link linkend="functions.arguments.type-declaration.strict">Strict typing</link>
957
-
also has an effect on return type declarations. In the default weak mode,
958
-
returned values will be coerced to the correct type if they are not
959
-
already of that type. In strong mode, the returned value must be of the
960
-
correct type, otherwise a <classname>TypeError</classname> will be thrown.
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.
961
752
</para>
962
753

963
754
<note>
964
755
<para>
965
-
When overriding a parent method, the child's method must match any return
966
-
type declaration on the parent. If the parent doesn't define a return
967
-
type, then the child method may do so.
756
+
If the <function>return</function> is omitted the value &null; will be
757
+
returned.
968
758
</para>
969
759
</note>
970
760

971
-
<sect3 xml:id="functions.returning-values.type-declaration.examples">
972
-
&reftitle.examples;
973
-

974
-
<example>
975
-
<title>Basic return type declaration</title>
976
-
<programlisting role="php">
761
+
<sect2>
762
+
<title>Use of return</title>
763
+
<para>
764
+
<example>
765
+
<title>Use of <function>return</function></title>
766
+
<programlisting role="php">
977
767
<![CDATA[
978
768
<?php
979
-
function sum($a, $b): float {
980
-
return $a + $b;
769
+
function square($num)
770
+
{
771
+
return $num * $num;
981
772
}
982
-

983
-
// Note that a float will be returned.
984
-
var_dump(sum(1, 2));
773
+
echo square(4); // outputs '16'.
985
774
?>
986
775
]]>
987
776
</programlisting>
988
-
&example.outputs;
989
-
<screen>
990
-
<![CDATA[
991
-
float(3)
992
-
]]>
993
-
</screen>
994
777
</example>
778
+
</para>
995
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>
996
785
<example>
997
-
<title>Strict mode in action</title>
786
+
<title>Returning an array to get multiple values</title>
998
787
<programlisting role="php">
999
788
<![CDATA[
1000
789
<?php
1001
-
declare(strict_types=1);
1002
-

1003
-
function sum($a, $b): int {
1004
-
return $a + $b;
790
+
function small_numbers()
791
+
{
792
+
return [0, 1, 2];
1005
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();
1006
799

1007
-
var_dump(sum(1, 2));
1008
-
var_dump(sum(1, 2.5));
1009
800
?>
1010
801
]]>
1011
802
</programlisting>
1012
-
&example.outputs;
1013
-
<screen>
1014
-
<![CDATA[
1015
-
int(3)
1016
-

1017
-
Fatal error: Uncaught TypeError: Return value of sum() must be of the type integer, float returned in - on line 5 in -:5
1018
-
Stack trace:
1019
-
#0 -(9): sum(1, 2.5)
1020
-
#1 {main}
1021
-
thrown in - on line 5
1022
-
]]>
1023
-
</screen>
1024
803
</example>
1025
-

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>
1026
811
<example>
1027
-
<title>Returning an object</title>
812
+
<title>Returning a reference from a function</title>
1028
813
<programlisting role="php">
1029
814
<![CDATA[
1030
815
<?php
1031
-
class C {}
1032
-

1033
-
function getC(): C {
1034
-
return new C;
816
+
function &returns_reference()
817
+
{
818
+
return $someref;
1035
819
}
1036
820

1037
-
var_dump(getC());
821
+
$newref =& returns_reference();
1038
822
?>
1039
823
]]>
1040
824
</programlisting>
1041
-
&example.outputs;
1042
-
<screen>
1043
-
<![CDATA[
1044
-
object(C)#1 (0) {
1045
-
}
1046
-
]]>
1047
-
</screen>
1048
825
</example>
1049
-
</sect3>
826
+
</para>
827
+
<simpara>
828
+
For more information on references, please check out <link
829
+
linkend="language.references">References Explained</link>.
830
+
</simpara>
1050
831
</sect2>
1051
832
</sect1>
1052
833

...
...
@@ -1158,11 +939,11 @@ Foo::$variable(); // This calls $foo->Variable() reading $variable in this scop
1158
939
</example>
1159
940
</para>
1160
941
<para>
1161
-
As of PHP 5.4.0, you can call any <type>callable</type> stored in a variable.
1162
942
<example>
1163
943
<title>Complex callables</title>
1164
944
<programlisting role="php">
1165
945
<![CDATA[
946
+
<?php
1166
947
class Foo
1167
948
{
1168
949
static function bar()
...
...
@@ -1177,48 +958,25 @@ class Foo
1177
958

1178
959
$func = array("Foo", "bar");
1179
960
$func(); // prints "bar"
1180
-
$f = array(new Foo, "baz");
961
+
$func = array(new Foo, "baz");
1181
962
$func(); // prints "baz"
1182
-
$f = "Foo::bar";
1183
-
$func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
963
+
$func = "Foo::bar";
964
+
$func(); // prints "bar"
965
+
?>
1184
966
]]>
1185
967
</programlisting>
1186
968
</example>
1187
969
</para>
1188
970

1189
-
<para>
1190
-
See also <function>is_callable</function>, <function>call_user_func</function>,
1191
-
<link linkend="language.variables.variable">
1192
-
variable variables</link> and <function>function_exists</function>.
1193
-
</para>
1194
-
1195
-
<sect2 role="changelog">
1196
-
&reftitle.changelog;
971
+
<sect2 role="seealso">
972
+
&reftitle.seealso;
1197
973
<para>
1198
-
<informaltable>
1199
-
<tgroup cols="2">
1200
-
<thead>
1201
-
<row>
1202
-
<entry>&Version;</entry>
1203
-
<entry>&Description;</entry>
1204
-
</row>
1205
-
</thead>
1206
-
<tbody>
1207
-
<row>
1208
-
<entry>7.0.0</entry>
1209
-
<entry>
1210
-
'ClassName::methodName' is allowed as variable function.
1211
-
</entry>
1212
-
</row>
1213
-
<row>
1214
-
<entry>5.4.0</entry>
1215
-
<entry>
1216
-
Arrays, which are valid callables, are allowed as variable functions.
1217
-
</entry>
1218
-
</row>
1219
-
</tbody>
1220
-
</tgroup>
1221
-
</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>
1222
980
</para>
1223
981
</sect2>
1224
982
</sect1>
...
...
@@ -1233,8 +991,8 @@ $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
1233
991
<link linkend="ref.image">image</link> functions such as
1234
992
<function>imagecreatetruecolor</function>, PHP must be compiled with
1235
993
<productname>GD</productname> support. Or, to use
1236
-
<function>mysql_connect</function>, PHP must be compiled with
1237
-
<link linkend="ref.mysql">MySQL</link> support. There are many core functions
994
+
<function>mysqli_connect</function>, PHP must be compiled with
995
+
<link linkend="book.mysqli">MySQLi</link> support. There are many core functions
1238
996
that are included in every version of PHP, such as the
1239
997
<link linkend="ref.strings">string</link> and
1240
998
<link linkend="ref.var">variable</link> functions. A call
...
...
@@ -1266,14 +1024,54 @@ $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
1266
1024
the return value of the function is undefined. In this case it will
1267
1025
likely return &null; but this is just a convention, and cannot be relied
1268
1026
upon.
1027
+
As of PHP 8.0.0, a <classname>TypeError</classname> exception is supposed to
1028
+
be thrown in this case.
1269
1029
</simpara>
1270
1030
</note>
1271
-
<para>
1272
-
See also <function>function_exists</function>,
1273
-
<link linkend="funcref">the function reference</link>,
1274
-
<function>get_extension_funcs</function>, and
1275
-
<function>dl</function>.
1276
-
</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
+
<informalexample>
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
+
</informalexample>
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>
1277
1075
</sect1>
1278
1076
1279
1077
<sect1 xml:id="functions.anonymous">
...
...
@@ -1282,9 +1080,13 @@ $func(); // prints "bar" as of PHP 7.0.0; prior, it raised a fatal error
1282
1080
<simpara>
1283
1081
Anonymous functions, also known as <literal>closures</literal>, allow the
1284
1082
creation of functions which have no specified name. They are most useful as
1285
-
the value of <link linkend="language.types.callback">callback</link>
1083
+
the value of <type>callable</type>
1286
1084
parameters, but they have many other uses.
1287
1085
</simpara>
1086
+
<simpara>
1087
+
Anonymous functions are implemented using the <link linkend="class.closure">
1088
+
<classname>Closure</classname></link> class.
1089
+
</simpara>
1288
1090

1289
1091
<example>
1290
1092
<title>Anonymous function example</title>
...
...
@@ -1313,8 +1115,7 @@ echo preg_replace_callback('~-([a-z])~', function ($match) {
1313
1115
<programlisting role="php">
1314
1116
<![CDATA[
1315
1117
<?php
1316
-
$greet = function($name)
1317
-
{
1118
+
$greet = function($name) {
1318
1119
printf("Hello %s\r\n", $name);
1319
1120
};
1320
1121

...
...
@@ -1326,8 +1127,12 @@ $greet('PHP');
1326
1127
</example>
1327
1128
1328
1129
<simpara>
1329
-
Closures may also inherit variables from the parent scope.
1330
-
Any such variables must be passed to the <literal>use</literal> language construct.
1130
+
Closures may also inherit variables from the parent scope. Any such
1131
+
variables must be passed to the <literal>use</literal> language construct.
1132
+
As of PHP 7.1, these variables must not include &link.superglobals;,
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.
1331
1136
</simpara>
1332
1137

1333
1138
<example>
...
...
@@ -1341,18 +1146,18 @@ $message = 'hello';
1341
1146
$example = function () {
1342
1147
var_dump($message);
1343
1148
};
1344
-
echo $example();
1149
+
$example();
1345
1150

1346
1151
// Inherit $message
1347
1152
$example = function () use ($message) {
1348
1153
var_dump($message);
1349
1154
};
1350
-
echo $example();
1155
+
$example();
1351
1156

1352
1157
// Inherited variable's value is from when the function
1353
1158
// is defined, not when called
1354
1159
$message = 'world';
1355
-
echo $example();
1160
+
$example();
1356
1161

1357
1162
// Reset message
1358
1163
$message = 'hello';
...
...
@@ -1361,18 +1166,24 @@ $message = 'hello';
1361
1166
$example = function () use (&$message) {
1362
1167
var_dump($message);
1363
1168
};
1364
-
echo $example();
1169
+
$example();
1365
1170

1366
1171
// The changed value in the parent scope
1367
1172
// is reflected inside the function call
1368
1173
$message = 'world';
1369
-
echo $example();
1174
+
$example();
1370
1175

1371
1176
// Closures can also accept regular arguments
1372
1177
$example = function ($arg) use ($message) {
1373
1178
var_dump($arg . ' ' . $message);
1374
1179
};
1375
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());
1376
1187
?>
1377
1188
]]>
1378
1189
</programlisting>
...
...
@@ -1386,10 +1197,15 @@ string(5) "hello"
1386
1197
string(5) "hello"
1387
1198
string(5) "world"
1388
1199
string(11) "hello world"
1200
+
string(11) "hello world"
1389
1201
]]>
1390
1202
</screen>
1391
1203
</example>
1392
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>
1393
1209
<simpara>
1394
1210
Inheriting variables from the parent scope is <emphasis>not</emphasis>
1395
1211
the same as using global variables.
...
...
@@ -1459,10 +1275,111 @@ print $my_cart->getTotal(0.05) . "\n";
1459
1275
</programlisting>
1460
1276
</example>
1461
1277

1462
-
<simpara>
1463
-
Anonymous functions are implemented using the <link linkend="class.closure">
1464
-
<classname>Closure</classname></link> class.
1465
-
</simpara>
1278
+
<example>
1279
+
<title>Automatic binding of <literal>$this</literal></title>
1280
+
<programlisting role="php">
1281
+
<![CDATA[
1282
+
<?php
1283
+

1284
+
class Test
1285
+
{
1286
+
public function testing()
1287
+
{
1288
+
return function() {
1289
+
var_dump($this);
1290
+
};
1291
+
}
1292
+
}
1293
+

1294
+
$object = new Test;
1295
+
$function = $object->testing();
1296
+
$function();
1297
+
1298
+
?>
1299
+
]]>
1300
+
</programlisting>
1301
+
&example.outputs;
1302
+
<screen>
1303
+
<![CDATA[
1304
+
object(Test)#1 (0) {
1305
+
}
1306
+
]]>
1307
+
</screen>
1308
+
</example>
1309
+

1310
+
<para>
1311
+
When declared in the context of a class, the current class is
1312
+
automatically bound to it, making <literal>$this</literal> available
1313
+
inside of the function's scope. If this automatic binding of the current
1314
+
class is not wanted, then
1315
+
<link linkend="functions.anonymous-functions.static">static anonymous
1316
+
functions</link> may be used instead.
1317
+
</para>
1318
+

1319
+
<sect2 xml:id="functions.anonymous-functions.static">
1320
+
<title>Static anonymous functions</title>
1321
+
<para>
1322
+
Anonymous functions may be declared statically. This
1323
+
prevents them from having the current class automatically bound to
1324
+
them. Objects may also not be bound to them at runtime.
1325
+
</para>
1326
+
<para>
1327
+
<example>
1328
+
<title>Attempting to use <literal>$this</literal> inside a static anonymous function</title>
1329
+
<programlisting role="php">
1330
+
<![CDATA[
1331
+
<?php
1332
+

1333
+
class Foo
1334
+
{
1335
+
function __construct()
1336
+
{
1337
+
$func = static function() {
1338
+
var_dump($this);
1339
+
};
1340
+
$func();
1341
+
}
1342
+
};
1343
+
new Foo();
1344
+

1345
+
?>
1346
+
]]>
1347
+
</programlisting>
1348
+
&example.outputs;
1349
+
<screen>
1350
+
<![CDATA[
1351
+
Notice: Undefined variable: this in %s on line %d
1352
+
NULL
1353
+
]]>
1354
+
</screen>
1355
+
</example>
1356
+
</para>
1357
+

1358
+
<para>
1359
+
<example>
1360
+
<title>Attempting to bind an object to a static anonymous function</title>
1361
+
<programlisting role="php">
1362
+
<![CDATA[
1363
+
<?php
1364
+

1365
+
$func = static function() {
1366
+
// function body
1367
+
};
1368
+
$func = $func->bindTo(new stdClass);
1369
+
$func();
1370
+

1371
+
?>
1372
+
]]>
1373
+
</programlisting>
1374
+
&example.outputs;
1375
+
<screen>
1376
+
<![CDATA[
1377
+
Warning: Cannot bind an instance to a static closure in %s on line %d
1378
+
]]>
1379
+
</screen>
1380
+
</example>
1381
+
</para>
1382
+
</sect2>
1466
1383
1467
1384
<sect2 role="changelog">
1468
1385
&reftitle.changelog;
...
...
@@ -1477,15 +1394,176 @@ print $my_cart->getTotal(0.05) . "\n";
1477
1394
</thead>
1478
1395
<tbody>
1479
1396
<row>
1480
-
<entry>5.4.0</entry>
1397
+
<entry>7.1.0</entry>
1481
1398
<entry>
1482
-
<varname>$this</varname> can be used in anonymous functions.
1399
+
Anonymous functions may not close over &link.superglobals;,
1400
+
<varname>$this</varname>, or any variable with the same name as a
1401
+
parameter.
1483
1402
</entry>
1484
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>
1485
1557
<row>
1486
-
<entry>5.3.0</entry>
1558
+
<entry>&Version;</entry>
1559
+
<entry>&Description;</entry>
1560
+
</row>
1561
+
</thead>
1562
+
<tbody>
1563
+
<row>
1564
+
<entry>7.4.0</entry>
1487
1565
<entry>
1488
-
Anonymous functions become available.
1566
+
Arrow functions became available.
1489
1567
</entry>
1490
1568
</row>
1491
1569
</tbody>
...
...
@@ -1500,11 +1578,131 @@ print $my_cart->getTotal(0.05) . "\n";
1500
1578
<simpara>
1501
1579
It is possible to use <function>func_num_args</function>,
1502
1580
<function>func_get_arg</function>, and <function>func_get_args</function>
1503
-
from within a closure.
1581
+
from within an arrow function.
1504
1582
</simpara>
1505
1583
</note>
1506
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
1507
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
+
<informalexample>
1695
+
<programlisting role="php">
1696
+
<![CDATA[
1697
+
<?php
1698
+
$obj?->method(...);
1699
+
$obj?->prop->method(...);
1700
+
?>
1701
+
]]>
1702
+
</programlisting>
1703
+
</informalexample>
1704
+
</para>
1705
+
</note>
1508
1706
</sect1>
1509
1707

1510
1708
</chapter>
1511
1709