What’s new in PHP 7.1
-
Wiki: PHP 7.1
-
github.com: Список изменений PHP 7.1
-
php.net: Новые возможности PHP 7.1
- skillz.ru: Список изменений PHP 7.1
?string — Nullable type (and null type)
Types for parameters and return values can be marked as nullable by prefixing with a question mark. This means that the specified parameters and return values can be either the indicated type or NULL.
function testReturn(): ?string {
return 'elePHPant';
}
var_dump( testReturn() ); // string(10) "elePHPant"
function testReturn(): ?string {
return null;
}
var_dump( testReturn() ); // NULL
function test( ?string $name ) {
var_dump( $name );
}
test('elePHPant'); // string(10) "elePHPant"
test(null); // NULL
test(); // Uncaught Error: Too few arguments to function test(), 0 passed in...
void — return type
Now functions and methods that should not return anything can be marked with a return type void. The return statement must be absent or empty - return;. Calling return null; will cause an error.
function someMethod(): void {
// works if return is absent
// works with return;
// does not work if return null;
// does not work if return 123;
}
['key'=>$var] = ['key'=>'Value'] — Destructuring arrays
Wiki: Destructuring assignment from an array to variables (short list syntax).
The syntax [] = [] can be used for destructuring arrays and assigning array values to variables — an alternative to the list() function.
Example with a numeric array:
list( $one, $two ) = [ 'один', 'два' ]; // list style [ $one, $two ] = [ 'один', 'два' ]; // [] style echo "$one, $two"; //> один, два
The same can be done with an associative array, extracting values by keys. The names of the extracted variables can be anything, the key match is what matters.
$person = [ 'first' => 'Rasmus', 'last' => 'Lerdorf', 'manager' => true ]; // Order of extraction does not matter [ 'last' => $lastname, 'first' => $firstname ] = $person; echo "$lastname, $firstname"; //> Lerdorf, Rasmus
Nested destructuring.
You can also assign values from nested arrays:
[ [$a, $b], [$c, $d] ] = [ [1, 2], [3, 4] ];
$options = [ 'enabled' => true, 'compression' => ['algo' => 'gzip'] ]; [ 'enabled' => $enabled, 'compression' => [ 'algo' => $algo, ] ] = $options;
Destructuring in foreach.
The syntax list() is allowed not only on the left side of an assignment, but also as the loop variable in foreach. The new syntax [] works here as well:
$persons = [
[ 'first' => 'Rasmus', 'last' => 'Lerdorf' ],
[ 'first' => 'Egor', 'last' => 'Drujo' ],
[ 'first' => 'Telia', 'last' => 'Masterok' ],
];
foreach( $persons as [ 'first' => $first, 'last' => $last ] ){
echo "$first, $last";
}
Destructuring with adding an element to an array.
Destructure directly while adding a new element to the array:
$data = []; [ $data[] ] = ['foo']; [ $data[] ] = ['bar']; print_r( $data ); /** * Array ( * [0] => foo * [1] => bar * ) */
list( 'id'=>$id ) = $data — Keys support in list()
Now the list() operator supports keys. This allows destructuring arrays with non-numeric 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];
// foreach style
foreach ( $data as list("id" => $id, "name" => $name) ) {
// logic here with $id and $name
}
// foreach style
foreach ( $data as ["id" => $id, "name" => $name] ) {
// logic here with $id and $name
}
Closure::fromCallable() — new static method Closure
In the Closure class, a new static method has been added to easily convert a callable into Closure objects.
class Test {
public function exposeFunction(){
return Closure::fromCallable( [$this, 'privateFunction'] );
}
private function privateFunction( $param ){
var_dump( $param );
}
}
$privFunc = (new Test)->exposeFunction();
$privFunc('значение'); //> string(16) "значение"
private const — Constant visibility in classes
No more public constants placeholders; you can now specify visibility for constants:
class ConstClass {
const CONST_ONE = 1; // public
public const CONST_TWO = 2;
protected const CONST_THREE = 3;
private const CONST_FOUR = 4;
}
iterable — new pseudo-type
Wiki: RFC: Iterable
A new type iterable for input/return values has been introduced. It can be used when passing arrays or objects that implement the Traversable interface.
function myfunc( iterable $data ){
foreach( $data as $k => $v ){
echo $k, ':', $v, PHP_EOL;
}
}
// array
myfunc([10, 20, 30]); // 0:10 1:20 2:30
// object
myfunc( new SplFixedArray(3) ) // 0: 1: 2:
// generator
function myGen(){
yield 10;
yield 20;
yield 30;
}
myfunc( myGen() ); // 0:10 1:20 2:30
?int = null — type of input/return values
Wiki: Nullable Types
In PHP 7.0 it became possible to specify return/input value types, but the type did not allow using null as a parameter value.
In PHP 7.1 to allow null before the parameter type, a ? is placed:
function myfunc( ?int $i ) : ?int {
var_dump($a);
return $a;
}
myfunc( 20 ); // int(20)
myfunc( null ); // null
myfunc(); // Error: Uncaught Error: Too few arguments to function name(), 0 passed
$string[-1] — negative offset in strings
Added the ability to use a negative offset in strings
echo $string[-1]; // last character
catch (First | Second $e) — handling multiple exceptions in one catch block
In a catch block you can now handle multiple exceptions, listing them with the pipe symbol (|). This can be useful when different exceptions are handled the same way.
try {
// Some code
}
catch ( FirstException | SecondException $e ) {
// Handle both exceptions
}
PHP 7.1 Notes
PHP is moving toward stronger data typing, and when upgrading to 7.1 I ran into a FATAL error. And that seemed very strange to me. Here is an example:
$foo = ''; $foo['bar'] = 'мир'; // Warning: Illegal string offset 'bar' $foo['bar'][] = 'мир'; // Fatal error: Uncaught Error: Cannot use string offset as an array // fatal error: cannot use string offset as an array...
With a Warning PHP still works, but after that it stops! And in 7.0 the code simply worked, even without warnings and notices... It seems to be a shortcoming in PHP 7.1.
—