Nullable types

<?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

Void functions

<?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
}

Symmetric array destructuring

<?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]) {
  // ...
}

Class constant visibility

<?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;
}

Multi catch exception handling

<?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) {
  // ...
}

New list() features

<?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]) {
  ..
}

Support for negative string offsets

<?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.

Hire me!

I'm currently open for new projects or join pretty much any project i may fit in, let me know!

Read about what I do, or contact me for details.

Categories