PHP 8.5.0 Alpha 4 available for testing

Voting

: five plus four?
(Example: nine)

The Note You're Voting On

et2225zas14 at susu dot ru
1 year ago
Be careful with type hints in callbacks when using array-traverse functions. In some cases, this may silently cause the data type of elements to change.

<?php
declare(strict_types=1);

// Missing fatal TypeError, No side effects
$unexpected = array_filter(['123', (string) PHP_INT_MAX], fn (int $item) => true);
var_dump($unexpected);

// Missing fatal TypeError, Typecasting side effect
$unexpectedTypecasting = array_map(fn (int $item) => $item, ['123', (string) PHP_INT_MAX]);
var_dump($unexpectedTypecasting);

// Missing fatal TypeError, Typecasting side effect
$unexpectedTypecasting = array_map(fn (string $item) => $item, [123, PHP_INT_MAX]);
var_dump($unexpectedTypecasting);

// Missing fatal TypeError, Typecasting side effect
$unexpectedTypecasting = array_reduce(['123', (string) PHP_INT_MAX], fn (?int $carry, int $item) => $item);
var_dump($unexpectedTypecasting);

$bigIntValue = bcadd((string) PHP_INT_MAX, '1');
// Fatal TypeError
$expectedTypeError = array_map(fn (int $item) => $item, [$bigIntValue]);
var_dump($expectedTypeError);
?>

The above example will output (PHP version 8.3.6, error_reporting E_ALL):

<?php
array(2) {
[
0]=>
string(3) "123"
[1]=>
string(19) "9223372036854775807"
}
array(
2) {
[
0]=>
int(123)
[
1]=>
int(9223372036854775807)
}
array(
2) {
[
0]=>
string(3) "123"
[1]=>
string(19) "9223372036854775807"
}
int(9223372036854775807)

Fatal error: Uncaught TypeError: {closure}(): Argument #1 ($item) must be of type int, string given
?>

<< Back to user notes page

To Top