<?php
/*
* Parameters and return values can now be marked as
* nullable by prefixing the type name with a question mark
* NULLable doesnt mean omit it, it that case it will throw an error
*/
function test(?string $name): ?string
{
return null;
}
test('it works');
test(null); // it also works
test(); // Throws an error
<?php
/*
* By declaring a function return type "void" the function must omit the return
* statement or use an empty one. NULL is not a valid return.
*/
function test(): void {
return; // Empty return
}
<?php
/* The array syntax ([]) can be used to destructure arrays for assignments */
$data = [
[1, 'Tom'],
[2, 'Fred'],
];
[$id1, $name1] = $data[0];
[$id2, $name2] = $data[1];
foreach ($data as [$id, $name]) {
// ...
}
<?php
/* Visibility of class constants has been added. */
class ConstDemo {
const PUBLIC_CONST_A = 1;
public const PUBLIC_CONST_B = 2;
protected const PROTECTED_CONST = 3;
private const PRIVATE_CONST = 4;
}
<?php
/*
* This can be done with the "|" pipe character.
* Useful when different exceptions from different class hierarchies
* are handled the same
*/
try {
// ...
} catch (FirstException | SecondException $e) {
// ...
}
<?php
/*
* Now specify keys in list() or "[]" for destructuring
* arrays with non-integer or non-sequential keys
*/
$data = [
["id" => 1, "name" => 'Tom'],
["id" => 2, "name" => 'Fred'],
];
// list() style
list("id" => $id1, "name" => $name1) = $data[0];
// [] style
["id" => $id1, "name" => $name1] = $data[0];
// inside a foreach
foreach ($data as ["id" => $id, "name" => $name]) {
..
}
<?php
/*
* Negative string offsets has been added to the manipulation functions,
* as well as to string indexing and variables
*/
var_dump(strpos("aabbcc", "b", -3)); // outputs: 3
var_dump("abcdef"[-2]); //outputs: e
$string = 'bar';
var_dump($string[-1]); // outputs: r
For a full list of changes go here.