PHP 8 — What’s New?

Union types

class Example {  private int|string $id;

public function setId(int|string $id): void {
$this->id = $id;
}
public function getId(): int|string {
return $this->id;
}
}

Named arguments

foo(string $b, ?string $a, ?string $r): {
}
Example::foo(
b: 'Foo',
r: 'Bar',
);

Constructor property promotion

// PHP 7
class Example {

public Foo $foo;

protected Bar $bar;

public function __construct(
Foo $foo,
Bar $bar
) {
$this->foo = $foo;
$this->bar = $bar;
}
}// PHP 8
class Example {

public function __construct(
public Foo $foo,
protected Bar $bar,
) {}
}

Attributes

use Php\Attributes\Deprecated;

<<Deprecated("Use bar() instead")>>
function foo() {}

Match expression

$controller = match ($status_code) {
200 => new PageController(),
301, 302, 303 => new RedirectController(),
404 => new PageNotFoundController(),
};

JIT (Just in time compiler)

Other new features

  • nullsafe operator — equivalent of null coalescing operator for methods e.g. $item->getField()?->getValue();
  • static — added as returned value type, previously only self was available;
  • mixed — a new value type, which means the same as the known mixed value in the comments, which is any simple type;
  • WeakMaps — a mechanism for storing references, which at the same time allows for their removal by the garbage collector;
  • using the magic ::class method on objects — allows you to obtain the same value as returned from the get_class() function;
  • trailing comma in the list of function parameters;
  • handling exceptions without the need for them to be assigned to a variable;
  • new Stringable interface — automatically assigned to all classes that implement __toString() method;
  • validation of abstract methods derived from traits.

New features

str_contains()

str_starts_with() and str_ends_with()

get_debug_type()

General changes

Conclusions

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Droptica

Droptica

Enterprise websites built with best Open Source solutions. We are an Agile software development company. We create big websites with Drupal 8, Symfony and React