Novedades de PHP 7.4

Lista de novedades que trae la versión 7.4 de PHP

Novedades de PHP 7.4

Introducción

Funciones flecha

$prices = array_map(function (Product $product) {      
return $product->getPrice();
}, $products);
$prices = array_map(fn($product) => $product->getPrice(), $products);
$prices = array_map(fn(Product $product): float => $product->getPrice(), $products);
$multiplier = 5;  array_map(fn($x) => $x * $multiplier, $numbers);

Typed class properties

class User {  public string $name;  public ?int $age;  public ContactInfo $contactInfo;}
class Foo {     
public string $bar;
}
$foo = new Foo;
var_dump($foo->bar);
Fatal error: Uncaught Error: Typed property Foo::$bar must not be accessed before initialization
class User {     
public int $age = 32;
public ?string $name = null;
public array $telephones = ['xxxx', 'bbbbb'];
}

“Type variance” mejorada en el retorno de funciones

class Parent {};
class Child extends Parent {};
class Foo
{
public function covariant(): ParentType {};
}
class Bar extends Foo
{
public function covariant(): ChildType {};
}
class Parent {};
class Child extends Parent {};
class Foo
{
public function contravariant(Child $value) {};
}
class Bar extends Foo
{
public function contravariant(Parent $value) {};

If S is a subtype of T, then objects of type Tmay be replaced with objects of type S

Nuevo operador: Null coalescing assignment operator

$someArray['key'] = $someArray['key'] ?? 'foo';
$someArray['key'] ??= 'foo';

Operador spread para arrays

$foo = [1, 2, 3];$bar = ['a', 'b', 'c'];$result = [0, ...$foo, ...$bar, 'd'];// 0, 1, 2, 3, 'a', 'b', 'c', 'd'

Preloading

opcache.preload=/path/to/project/preload.php
//preload.php$files = ['file1.php', 'file2.php'];foreach ($files as $file) {     
opcache_compile_file($file);
}
Can't preload unlinked class Foo
Unknown parent Bar

Conclusión

¿Quieres recibir más artículos como este?

Entre paseo y paseo con Simba desarrollo en Symfony y React

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