Etes-vous prêt pour PHP 8 ?
Christophe Villeneuve
@hellosct1
@hellosct1@mamot.fr
Meetup Programmez #10 – le 08 Sept. 2020
Atos open source - afup – lemug.fr – mariadb – drupal – mozilla - firefox – lemugfr - sumo – webextensions – VR – AR – XR - Cause commune 93.1 FM - TechSpeaker - Lizard - eyrolles – editions eni – programmez – linux pratique – webriver – elephpant - CommonVoice – Sécurité -
Cybersécurité
Christophe Villeneuve
●
Consultant Open Source
●
Dresseur animaux
@hellosct1 – Programmez #10 -
Forum PHP 2020
●
Double anniversaire
– AFUP : 20 ans
– PHP : 25 ans
https://event.afup.org/
@hellosct1 – Programmez #10 -
Aujourd’hui
●
Situation globale
●
Les nouveautés
●
Dépréciations & retraits
●
La performance
@hellosct1 – Programmez #10 -
Compilateur JIT
●
La plus grande innovation
●
Amélioration des performances.
●
Rappel : PHP n’est pas compilé, mais interprété
→ ligne par ligne.
●
Le compilateur JIT (Just in Time)
compile des parties du code pendant l’exécution
→ Agir comme une version en cache du code.
●
Situation globale
●
Les nouveautés
●
Dépréciations & retraits
●
La performance
@hellosct1 – Programmez #10 -
Support PHP
https://www.php.net/supported-versions.php
@hellosct1 – Programmez #10 -
Happy Birthday
●
8 juin 2020 – 25 ans de PHP
●
Logo de Vincent Pontier (aka El Roubio)
@hellosct1 – Programmez #10 -
Roadmap / Calendrier PHP 8.0
Jan Fev Mars Avr Mai Juin Juil Aout Sept Oct Nov Dec
●
Basé sur le calendrier de publication de PHP 7.4
●
PHP 8 : 2021
https://wiki.php.net/todo/php80
25
Alpha
06
Beta
17
RC
Final
26 nov.
RC3
RC4
RC2
RC5
03
Beta3
@hellosct1 – Programmez #10 -
PHP 8.0.0 beta 3
●
Disponible le 3 septembre 2020
●
https://github.com/php/php-src/blob/php-8.0.0beta3/UPGRADING
●
●
Situation globale
●
Les nouveautés
●
Dépréciations & retraits
●
La performance
●
Méthodes
●
Les fonctions
●
La gestion des erreurs
@hellosct1 – Programmez #10 -
Union Types 2.0 (1/2)
●
Inspiré de C/C++, TypeScript ou Haskell.
→ Peut se résumer à des types à choix multiples
●
2 types ou plus peuvent former une union
→ Chaque type mentionné peut être utilisé.
●
Exemple :
●
Restriction :
– Par de valeur de retour : void
– Les unions nulles peuvent être déclarées avec les mentions |
null ou ?
public function foo(Foo|Bar $input): int|float;
public function foo(Foo|null $foo): void;
public function bar(?Bar $bar): void;
@hellosct1 – Programmez #10 -
Union Types (2/2)
class Number {
/**
* @var int|float $number
*/
private $number;
 
/**
* @param int|float $number
*/
public function setNumber($number) {
$this->number = $number;
}
 
/**
* @return int|float
*/
public function getNumber() {
return $this->number;
}
}
Avant
https://wiki.php.net/rfc/union_types_v2
●
Propriété de classe soit un entier ou nombre flottant
class Number {
private int|float $number;
public function setNumber(int|float
$number): void {
$this->number = $number;
}
public function getNumber(): int|
float {
return $this->number;
}
}
PHP 8
@hellosct1 – Programmez #10 -
Weak Maps (1/3)
●
Basé sur weakrefs RFC (en PHP 7.4)
– Implémentation de WeakMap en PHP 8.0
●
Contient des références à des objets
– Permettre
une meilleure façon de gestion et de traitement de ses objets.
– Augmenter la productivité en réduisant le temps d’attente.
●
Intérêts :
– Evite les fuites de mémoires
– Chaque instance de la classe reste ainsi itérable
https://wiki.php.net/rfc/weak_maps
@hellosct1 – Programmez #10 -
Weath Maps (2/3)
●
Utilisation :
– Suppression des objets lorsque seul le cache fait référence
aux classes d’entités des objets.
– Economie des ressources lors de la manipulation des objets.
class FooBar {
private WeakMap $cache;
public function getSomethingWithCaching(object $obj)
{
return $this->cache[$obj] ??=
$this->computeSomethingExpensive($obj);
}
// ...
}
@hellosct1 – Programmez #10 -
WeathMaps (3/3)
●
Utilisation Tableau
$map = new WeakMap; // objet instancé
$obj = new stdClass;
$map[$obj] = 42;
var_dump($map);
Résultat :
object(WeakMap)#1 (1) {
[0]=>
array(2) {
["key"]=>
object(stdClass)#2 (0) { }
["value"]=> int(42)
}
}
unset($obj); // détruit variable
var_dump($map);
Résultat :
object(WeakMap)#1 (0) {}
}
@hellosct1 – Programmez #10 -
Attributs (1/3)
●
Inspirés et appelés :
– Java → ‘Annotations’
– C++, Rust → Attributs
– Python, Javascript → décorateurs
●
https://wiki.php.net/rfc/attributes_v2
@hellosct1 – Programmez #10 -
Attributs (2/3)
●
Déclaration d'une classe d'attributs :
namespace MyAttributes;
 
use PhpAttribute;
 
<<PhpAttribute>>
class SingleArgument
{
public $value;
 
public function __construct(string $value)
{
$this->value = $value;
}
}
@hellosct1 – Programmez #10 -
Attributs (3/3)
●
Exemple
<?php
use DoctrineORMAttributes as ORM;
use SymfonyComponentValidatorConstraints as Assert;
<<ORMEntity>>
class User
{
<<ORMId>><<ORMColumn("integer")>><<ORMGeneratedValue>>
private $id;
<<ORMColumn("string", ORMColumn::UNIQUE)>>
<<AssertEmail(array("message" => "The email '{{ value }}' is not a valid email."))>>
private $email;
<<AssertRange(["min" => 120, "max" => 180, "minMessage" => "You must be at least {{ limit }}cm
tall to enter"])>>
<<ORMColumn(ORMColumn::T_INTEGER)>>
protected $height;
<<ORMManyToMany(Phonenumber::class)>>
<<ORMJoinTable("users_phonenumbers")>>
<<ORMJoinColumn("user_id", "id")>>
<<ORMInverseJoinColumn("phonenumber_id", "id", JoinColumn::UNIQUE)>>
private $phonenumbers;
}
@hellosct1 – Programmez #10 -
Type ‘static’ pour les résultats
●
PHP 7 : retourner les types ‘self’ ou ‘static’
●
PHP 8, le type static devient un type de retour valide
https://wiki.php.net/rfc/static_return_type
<?php
class A {
public static function getSelf(): self
{
return new self();
}
public static function getStatic(): static
{
return new static();
}
}
class B extends A {}
Résutlat :
get_class(B::getSelf()); // A
get_class(B::getStatic()); // B
get_class(A::getSelf()); // A
get_class(A::getStatic()); // A
@hellosct1 – Programmez #10 -
Reflection
●
Les signatures ont été modifiées.
●
Trois signatures de méthode des classes de réflexion ont été modifiées
ReflectionClass::newInstance($args);
ReflectionFunction::invoke($args);
ReflectionMethod::invoke($object, $args);
●
Avant
●
PHP 8
ReflectionClass::newInstance(...$args);
ReflectionFunction::invoke(...$args);
ReflectionMethod::invoke($object, ...$args);
●
Situation globale
●
Les nouveautés
●
Dépréciations & retraits
●
La performance
●
Méthodes
●
Les fonctions
●
La gestion des erreurs
@hellosct1 – Programmez #10 -
Match()
●
Expression de correspondance
switch ($statusCode) {
case 200:
case 300:
$message = null;
break;
case 400:
$message = 'not found';
break;
case 500:
$message = 'server error';
break;
default:
$message = 'unknown status';
break;
}
$message = match
($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'unknown
status code',
};
Avant PHP 8
https://wiki.php.net/rfc/match_expression_v2
@hellosct1 – Programmez #10 -
Fonction str_contains()
●
Vérifier si une chaîne est contenue dans une autre
●
Avant : utilisations de ‘strpos’ ou ‘strstr’
●
PHP 8 : <?php
 
str_contains("abc", "a"); // true
str_contains("abc", "d"); // false
 
// Les arguments avec une chaine vide
str_contains("abc", ""); // true
str_contains("", ""); // true
str_contains('', 'abc'); // false
// Un argument variable
str_contains('abc', $variable);
str_contains($variable, 'a');
https://wiki.php.net/rfc/str_contains
@hellosct1 – Programmez #10 -
Fonction str_start_with() & str_end_with()
●
Détermine le point de départ d’une chaîne
– str_start_with() : point de départ → début de la chaîne
– str_end_with() : point de départ → fin de la chaîne
●
https://wiki.php.net/rfc/add_str_starts_with_and_ends_with_functions
$str = "gaucheCentreDroit";
str_starts_with($str, "gau") //true
str_starts_with($str, "Gau") //false
str_ends_with($str, "Droit") //true
str_ends_with($str, "droit") //false
// Chaines vides
str_starts_with("a", "") //true
str_starts_with("", "") //true
str_starts_with("", "a") //false
str_ends_with("a", "") //true
str_ends_with("", "") //true
str_ends_with("", "a") //false
@hellosct1 – Programmez #10 -
La fonction fdiv (1/2)
●
S’inspire des fonctions fmod() and intdiv()
●
Norme IEEE-754 sur l'arithmétique à virgule flottante
●
Fdiv() : la division par 0 est autorisée.
●
Ne renvoie plus d’erreurs
●
Comme valeur de retour, le résultat possible :
→ INF,
→ -INF
→ NAN
@hellosct1 – Programmez #10 -
La fonction fdiv (2/2)
●
+ INF
●
- INF
fdiv(1, 0); // float(INF)
$num = 1 / 0; // float(INF)
// Warning: Division by zero in ... on line ...
fdiv(-1, 0); // float(-INF)
$num = -1 / 0; // float(-INF)
// Warning: Division by zero in ... on line ...
@hellosct1 – Programmez #10 -
Ordre des opérateurs de concaténation
●
Introduite à PHP 7.4
●
PHP réagit désormais de manière plus intelligente
→ lorsqu’il travaille avec plusieurs opérateurs.
●
Avant
●
PHP interpréte
●
PHP 8
echo "sum: " . $a + $b;
echo ("sum: " . $a) + $b;
echo "sum: " . ($a + $b);
@hellosct1 – Programmez #10 -
get_debug_type() (1/3)
●
Idem gettype()
●
Renvoie
– Type de variable
– Les noms de type natifs et résout les noms de classe.
@hellosct1 – Programmez #10 -
get_debug_type() (2/3)
●
PHP 8
if (!($bar instanceof Foo)) {
throw new TypeError(
'Expected ' . Foo::class .
' got ' . get_debug_type($bar));
}
Avant :
$bar = [1,2,3];
if (!($bar instanceof Foo)) {
throw new TypeError(
'Expected ' . Foo::class .
', got ' . (is_object($bar) ? get_class($bar) : gettype($bar)));
}
@hellosct1 – Programmez #10 -
get_debug_type() (3/3)
●
Résultat
@hellosct1 – Programmez #10 -
Objet ::class
●
C’est un alias de get_class()
→ attribuer une classe aux objets
●
Intérêt
– Réduction de la taille du code source
@hellosct1 – Programmez #10 -
Méthodes DateTime
●
Les classes DateTime & DatetimeImmutable ont des
méthodes pour créer une instance à partir d’une autre
●
PHP 8
●
les classes DateTime et DateTimeImmutable
→ obtiennent une nouvelle méthode :: createFromInterface.
●
Comportement identiques aux méthodes
– createFromMutable et createFromImmutable,
●
Mais la nouvelle méthode createFromInterface,
– Accepte toute implémentation DateTimeInterface.
DateTime::createFromInterface(DateTimeInterface $object): DateTime
DateTimeImmutable::createFromInterface(DateTimeInterface $object): DateTimeImmutable
●
Situation globale
●
Les nouveautés
●
Dépréciations & retraits
●
La performance
●
Méthodes
●
Les fonctions
●
La gestion des erreurs
@hellosct1 – Programmez #10 -
Type errors
●
Les erreurs de type cohérentes
●
Développement
– Fonctions définies par l'utilisateur
→ déclenchent des erreurs dans PHP
– Fonctions internes ne font pas d’erreurs.
→ Elles émettent plutôt des avertissements et renvoient un
message nul.
●
Avec PHP 8,
– Le comportement des fonctions internes a été rendu cohérent
@hellosct1 – Programmez #10 -
Les avertissements seront revus dans PHP 8
●
Avant PHP déclenchaient seulement des ‘avertissements’ ou des ‘Notice’.
●
PHP 8 affichera les erreurs correctes. Les avertissements suivants ont été modifiés :
– variable indéfinie : déclenche une erreur d'exception au lieu d'un avis ;
– indice de tableau indéfini : déclenche un avertissement au lieu d'avis ;
– Tentative d'incrémentation/diminution de la propriété “%s” d’un non-objet : déclenche une
erreur d’exception au lieu d’un avertissement ;
– Tentative de modification de la propriété “%s” d’un non-objet : déclenche une erreur
d’exception au lieu d'avertissement ;
– Tentative d'attribution de propriété “%s” d’un non-objet : déclenche une erreur d’exception
au lieu d'un avertissement ;
– Création d'un objet par défaut à partir d'une valeur vide : déclenche une erreur d’exception au
lieu d'un avertissement ;
– Impossible d'ajouter un élément au tableau, car l'élément suivant est déjà occupé : déclenche
une erreur d’exception au lieu d'un avertissement ;
– Ne peut pas annuler le décalage d'une variable qui n'est pas un tableau : déclenche une erreur
d’exception au lieu d'un avertissement ;
– Ne peut pas utiliser une valeur scalaire comme tableau : déclenche une erreur d’exception au
lieu d'un avertissement ;
– ...
@hellosct1 – Programmez #10 -
Default error reporting level
●
Utilisation de E_ALL
– Au lieu de tout
– Sauf pour E_NOTICE et E_DEPRECATED
●
Résultat
– Avant : les erreurs étaient silencieusement ignorés
– PHP 8 : Elles peuvent être affichés
@hellosct1 – Programmez #10 -
@ ne supprime plus les fatals errors
●
Au lieu de supprimer les erreurs avec l’opérateur @,
●
PHP 8 en production
– display_errors=Off sur le serveur.
●
Situation globale
●
Les nouveautés
●
Dépréciations & retraits
●
La performance
@hellosct1 – Programmez #10 -
Dépréciations & retraits
●
Des fonctions sont supprimées :
– __autoload ;
– convert_cyr_string (sans dépréciation) ;
– create_function ;
– Each ;
– ezmlm_hash (sans dépréciation) ;
– Fgetss ;
– get_magic_quotes_gpc ;
– hebrevc (sans dépréciation) ;
– money_format ;
– restore_include_path (sans dépréciation).
●
Situation globale
●
Les nouveautés
●
Incompatibilités
●
La performance
@hellosct1 – Programmez #10 -
Compilateur JIT
●
JIT = Just In Time
→ Compilation à la volée
●
Résultat attendu :
→ Amélioration du langage au niveau vitesse
●
Technique
– Le JIT traduit
●
Les parties extrêmes du code intermédiaire en code machine.
– Compiler des parties du code au moment de l'exécution
●
Permettre d’utiliser la version compilée à la place
@hellosct1 – Programmez #10 -
Compilateur JIT : configuration
●
Développeur
– Aucune action à faire
●
Administrateur du serveur
– modifier dans le fichier de configuration
●
Activer ou non certains paramètres :
– Modifier la taille du cache,
– Ajuster certains Triggers (déclencheurs).
https://wiki.php.net/rfc/jit
@hellosct1 – Programmez #10 -
Performance : compilateur JIT
https://gist.github.com/PedroEscudero/b64ea7409c0cc483c44f0773b6aebbdb
@hellosct1 – Programmez #10 -
Les autres améliorations
●
RFC : https://wiki.php.net/rfc#php_80
● Union types
JIT
The nullsafe operator
Named arguments
Attributes
Match expression
Constructor property promotion
New static return type
New mixed type
Throw expression
Inheritance with private methods
Weak maps
Allowing ::class on objects
Non-capturing catches
Trailing comma in parameter lists
Create DateTime objects from interface
New Stringable interface
New str_contains() function
New str_starts_with() and str_ends_with() functions
New fdiv() function
New get_debug_type() function
New get_resource_id() function
Abstract methods in traits improvements
Object implementation of token_get_all()
Variable syntax tweaks
Type annotations for internal functions
ext-json always available
* changement Rupture
Consistent type errors
Reclassified engine warnings
The @ operator no longer silences fatal errors
Default error reporting level
Default PDO error mode
Concatenation precedence
Stricter type checks for arithmetic and bitwise
operators
Namespaced names being a single token
Saner numeric strings
Saner string to number comparisons
Reflection method signature changes
Stable sorting
Fatal error for incompatible method signatures
@hellosct1 – Programmez #10 -
Article complet
prochainement
@hellosct1 – Programmez #10 -
Merci
Christophe Villeneuve
@hellosct1
@hellosct1@mamot.fr

Etes vous-pret pour php8 ?

  • 1.
    Etes-vous prêt pourPHP 8 ? Christophe Villeneuve @hellosct1 @hellosct1@mamot.fr Meetup Programmez #10 – le 08 Sept. 2020
  • 2.
    Atos open source- afup – lemug.fr – mariadb – drupal – mozilla - firefox – lemugfr - sumo – webextensions – VR – AR – XR - Cause commune 93.1 FM - TechSpeaker - Lizard - eyrolles – editions eni – programmez – linux pratique – webriver – elephpant - CommonVoice – Sécurité - Cybersécurité Christophe Villeneuve ● Consultant Open Source ● Dresseur animaux
  • 3.
    @hellosct1 – Programmez#10 - Forum PHP 2020 ● Double anniversaire – AFUP : 20 ans – PHP : 25 ans https://event.afup.org/
  • 4.
    @hellosct1 – Programmez#10 - Aujourd’hui ● Situation globale ● Les nouveautés ● Dépréciations & retraits ● La performance
  • 5.
    @hellosct1 – Programmez#10 - Compilateur JIT ● La plus grande innovation ● Amélioration des performances. ● Rappel : PHP n’est pas compilé, mais interprété → ligne par ligne. ● Le compilateur JIT (Just in Time) compile des parties du code pendant l’exécution → Agir comme une version en cache du code.
  • 6.
  • 7.
    @hellosct1 – Programmez#10 - Support PHP https://www.php.net/supported-versions.php
  • 8.
    @hellosct1 – Programmez#10 - Happy Birthday ● 8 juin 2020 – 25 ans de PHP ● Logo de Vincent Pontier (aka El Roubio)
  • 9.
    @hellosct1 – Programmez#10 - Roadmap / Calendrier PHP 8.0 Jan Fev Mars Avr Mai Juin Juil Aout Sept Oct Nov Dec ● Basé sur le calendrier de publication de PHP 7.4 ● PHP 8 : 2021 https://wiki.php.net/todo/php80 25 Alpha 06 Beta 17 RC Final 26 nov. RC3 RC4 RC2 RC5 03 Beta3
  • 10.
    @hellosct1 – Programmez#10 - PHP 8.0.0 beta 3 ● Disponible le 3 septembre 2020 ● https://github.com/php/php-src/blob/php-8.0.0beta3/UPGRADING ●
  • 11.
    ● Situation globale ● Les nouveautés ● Dépréciations& retraits ● La performance ● Méthodes ● Les fonctions ● La gestion des erreurs
  • 12.
    @hellosct1 – Programmez#10 - Union Types 2.0 (1/2) ● Inspiré de C/C++, TypeScript ou Haskell. → Peut se résumer à des types à choix multiples ● 2 types ou plus peuvent former une union → Chaque type mentionné peut être utilisé. ● Exemple : ● Restriction : – Par de valeur de retour : void – Les unions nulles peuvent être déclarées avec les mentions | null ou ? public function foo(Foo|Bar $input): int|float; public function foo(Foo|null $foo): void; public function bar(?Bar $bar): void;
  • 13.
    @hellosct1 – Programmez#10 - Union Types (2/2) class Number { /** * @var int|float $number */ private $number;   /** * @param int|float $number */ public function setNumber($number) { $this->number = $number; }   /** * @return int|float */ public function getNumber() { return $this->number; } } Avant https://wiki.php.net/rfc/union_types_v2 ● Propriété de classe soit un entier ou nombre flottant class Number { private int|float $number; public function setNumber(int|float $number): void { $this->number = $number; } public function getNumber(): int| float { return $this->number; } } PHP 8
  • 14.
    @hellosct1 – Programmez#10 - Weak Maps (1/3) ● Basé sur weakrefs RFC (en PHP 7.4) – Implémentation de WeakMap en PHP 8.0 ● Contient des références à des objets – Permettre une meilleure façon de gestion et de traitement de ses objets. – Augmenter la productivité en réduisant le temps d’attente. ● Intérêts : – Evite les fuites de mémoires – Chaque instance de la classe reste ainsi itérable https://wiki.php.net/rfc/weak_maps
  • 15.
    @hellosct1 – Programmez#10 - Weath Maps (2/3) ● Utilisation : – Suppression des objets lorsque seul le cache fait référence aux classes d’entités des objets. – Economie des ressources lors de la manipulation des objets. class FooBar { private WeakMap $cache; public function getSomethingWithCaching(object $obj) { return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj); } // ... }
  • 16.
    @hellosct1 – Programmez#10 - WeathMaps (3/3) ● Utilisation Tableau $map = new WeakMap; // objet instancé $obj = new stdClass; $map[$obj] = 42; var_dump($map); Résultat : object(WeakMap)#1 (1) { [0]=> array(2) { ["key"]=> object(stdClass)#2 (0) { } ["value"]=> int(42) } } unset($obj); // détruit variable var_dump($map); Résultat : object(WeakMap)#1 (0) {} }
  • 17.
    @hellosct1 – Programmez#10 - Attributs (1/3) ● Inspirés et appelés : – Java → ‘Annotations’ – C++, Rust → Attributs – Python, Javascript → décorateurs ● https://wiki.php.net/rfc/attributes_v2
  • 18.
    @hellosct1 – Programmez#10 - Attributs (2/3) ● Déclaration d'une classe d'attributs : namespace MyAttributes;   use PhpAttribute;   <<PhpAttribute>> class SingleArgument { public $value;   public function __construct(string $value) { $this->value = $value; } }
  • 19.
    @hellosct1 – Programmez#10 - Attributs (3/3) ● Exemple <?php use DoctrineORMAttributes as ORM; use SymfonyComponentValidatorConstraints as Assert; <<ORMEntity>> class User { <<ORMId>><<ORMColumn("integer")>><<ORMGeneratedValue>> private $id; <<ORMColumn("string", ORMColumn::UNIQUE)>> <<AssertEmail(array("message" => "The email '{{ value }}' is not a valid email."))>> private $email; <<AssertRange(["min" => 120, "max" => 180, "minMessage" => "You must be at least {{ limit }}cm tall to enter"])>> <<ORMColumn(ORMColumn::T_INTEGER)>> protected $height; <<ORMManyToMany(Phonenumber::class)>> <<ORMJoinTable("users_phonenumbers")>> <<ORMJoinColumn("user_id", "id")>> <<ORMInverseJoinColumn("phonenumber_id", "id", JoinColumn::UNIQUE)>> private $phonenumbers; }
  • 20.
    @hellosct1 – Programmez#10 - Type ‘static’ pour les résultats ● PHP 7 : retourner les types ‘self’ ou ‘static’ ● PHP 8, le type static devient un type de retour valide https://wiki.php.net/rfc/static_return_type <?php class A { public static function getSelf(): self { return new self(); } public static function getStatic(): static { return new static(); } } class B extends A {} Résutlat : get_class(B::getSelf()); // A get_class(B::getStatic()); // B get_class(A::getSelf()); // A get_class(A::getStatic()); // A
  • 21.
    @hellosct1 – Programmez#10 - Reflection ● Les signatures ont été modifiées. ● Trois signatures de méthode des classes de réflexion ont été modifiées ReflectionClass::newInstance($args); ReflectionFunction::invoke($args); ReflectionMethod::invoke($object, $args); ● Avant ● PHP 8 ReflectionClass::newInstance(...$args); ReflectionFunction::invoke(...$args); ReflectionMethod::invoke($object, ...$args);
  • 22.
    ● Situation globale ● Les nouveautés ● Dépréciations& retraits ● La performance ● Méthodes ● Les fonctions ● La gestion des erreurs
  • 23.
    @hellosct1 – Programmez#10 - Match() ● Expression de correspondance switch ($statusCode) { case 200: case 300: $message = null; break; case 400: $message = 'not found'; break; case 500: $message = 'server error'; break; default: $message = 'unknown status'; break; } $message = match ($statusCode) { 200, 300 => null, 400 => 'not found', 500 => 'server error', default => 'unknown status code', }; Avant PHP 8 https://wiki.php.net/rfc/match_expression_v2
  • 24.
    @hellosct1 – Programmez#10 - Fonction str_contains() ● Vérifier si une chaîne est contenue dans une autre ● Avant : utilisations de ‘strpos’ ou ‘strstr’ ● PHP 8 : <?php   str_contains("abc", "a"); // true str_contains("abc", "d"); // false   // Les arguments avec une chaine vide str_contains("abc", ""); // true str_contains("", ""); // true str_contains('', 'abc'); // false // Un argument variable str_contains('abc', $variable); str_contains($variable, 'a'); https://wiki.php.net/rfc/str_contains
  • 25.
    @hellosct1 – Programmez#10 - Fonction str_start_with() & str_end_with() ● Détermine le point de départ d’une chaîne – str_start_with() : point de départ → début de la chaîne – str_end_with() : point de départ → fin de la chaîne ● https://wiki.php.net/rfc/add_str_starts_with_and_ends_with_functions $str = "gaucheCentreDroit"; str_starts_with($str, "gau") //true str_starts_with($str, "Gau") //false str_ends_with($str, "Droit") //true str_ends_with($str, "droit") //false // Chaines vides str_starts_with("a", "") //true str_starts_with("", "") //true str_starts_with("", "a") //false str_ends_with("a", "") //true str_ends_with("", "") //true str_ends_with("", "a") //false
  • 26.
    @hellosct1 – Programmez#10 - La fonction fdiv (1/2) ● S’inspire des fonctions fmod() and intdiv() ● Norme IEEE-754 sur l'arithmétique à virgule flottante ● Fdiv() : la division par 0 est autorisée. ● Ne renvoie plus d’erreurs ● Comme valeur de retour, le résultat possible : → INF, → -INF → NAN
  • 27.
    @hellosct1 – Programmez#10 - La fonction fdiv (2/2) ● + INF ● - INF fdiv(1, 0); // float(INF) $num = 1 / 0; // float(INF) // Warning: Division by zero in ... on line ... fdiv(-1, 0); // float(-INF) $num = -1 / 0; // float(-INF) // Warning: Division by zero in ... on line ...
  • 28.
    @hellosct1 – Programmez#10 - Ordre des opérateurs de concaténation ● Introduite à PHP 7.4 ● PHP réagit désormais de manière plus intelligente → lorsqu’il travaille avec plusieurs opérateurs. ● Avant ● PHP interpréte ● PHP 8 echo "sum: " . $a + $b; echo ("sum: " . $a) + $b; echo "sum: " . ($a + $b);
  • 29.
    @hellosct1 – Programmez#10 - get_debug_type() (1/3) ● Idem gettype() ● Renvoie – Type de variable – Les noms de type natifs et résout les noms de classe.
  • 30.
    @hellosct1 – Programmez#10 - get_debug_type() (2/3) ● PHP 8 if (!($bar instanceof Foo)) { throw new TypeError( 'Expected ' . Foo::class . ' got ' . get_debug_type($bar)); } Avant : $bar = [1,2,3]; if (!($bar instanceof Foo)) { throw new TypeError( 'Expected ' . Foo::class . ', got ' . (is_object($bar) ? get_class($bar) : gettype($bar))); }
  • 31.
    @hellosct1 – Programmez#10 - get_debug_type() (3/3) ● Résultat
  • 32.
    @hellosct1 – Programmez#10 - Objet ::class ● C’est un alias de get_class() → attribuer une classe aux objets ● Intérêt – Réduction de la taille du code source
  • 33.
    @hellosct1 – Programmez#10 - Méthodes DateTime ● Les classes DateTime & DatetimeImmutable ont des méthodes pour créer une instance à partir d’une autre ● PHP 8 ● les classes DateTime et DateTimeImmutable → obtiennent une nouvelle méthode :: createFromInterface. ● Comportement identiques aux méthodes – createFromMutable et createFromImmutable, ● Mais la nouvelle méthode createFromInterface, – Accepte toute implémentation DateTimeInterface. DateTime::createFromInterface(DateTimeInterface $object): DateTime DateTimeImmutable::createFromInterface(DateTimeInterface $object): DateTimeImmutable
  • 34.
    ● Situation globale ● Les nouveautés ● Dépréciations& retraits ● La performance ● Méthodes ● Les fonctions ● La gestion des erreurs
  • 35.
    @hellosct1 – Programmez#10 - Type errors ● Les erreurs de type cohérentes ● Développement – Fonctions définies par l'utilisateur → déclenchent des erreurs dans PHP – Fonctions internes ne font pas d’erreurs. → Elles émettent plutôt des avertissements et renvoient un message nul. ● Avec PHP 8, – Le comportement des fonctions internes a été rendu cohérent
  • 36.
    @hellosct1 – Programmez#10 - Les avertissements seront revus dans PHP 8 ● Avant PHP déclenchaient seulement des ‘avertissements’ ou des ‘Notice’. ● PHP 8 affichera les erreurs correctes. Les avertissements suivants ont été modifiés : – variable indéfinie : déclenche une erreur d'exception au lieu d'un avis ; – indice de tableau indéfini : déclenche un avertissement au lieu d'avis ; – Tentative d'incrémentation/diminution de la propriété “%s” d’un non-objet : déclenche une erreur d’exception au lieu d’un avertissement ; – Tentative de modification de la propriété “%s” d’un non-objet : déclenche une erreur d’exception au lieu d'avertissement ; – Tentative d'attribution de propriété “%s” d’un non-objet : déclenche une erreur d’exception au lieu d'un avertissement ; – Création d'un objet par défaut à partir d'une valeur vide : déclenche une erreur d’exception au lieu d'un avertissement ; – Impossible d'ajouter un élément au tableau, car l'élément suivant est déjà occupé : déclenche une erreur d’exception au lieu d'un avertissement ; – Ne peut pas annuler le décalage d'une variable qui n'est pas un tableau : déclenche une erreur d’exception au lieu d'un avertissement ; – Ne peut pas utiliser une valeur scalaire comme tableau : déclenche une erreur d’exception au lieu d'un avertissement ; – ...
  • 37.
    @hellosct1 – Programmez#10 - Default error reporting level ● Utilisation de E_ALL – Au lieu de tout – Sauf pour E_NOTICE et E_DEPRECATED ● Résultat – Avant : les erreurs étaient silencieusement ignorés – PHP 8 : Elles peuvent être affichés
  • 38.
    @hellosct1 – Programmez#10 - @ ne supprime plus les fatals errors ● Au lieu de supprimer les erreurs avec l’opérateur @, ● PHP 8 en production – display_errors=Off sur le serveur.
  • 39.
  • 40.
    @hellosct1 – Programmez#10 - Dépréciations & retraits ● Des fonctions sont supprimées : – __autoload ; – convert_cyr_string (sans dépréciation) ; – create_function ; – Each ; – ezmlm_hash (sans dépréciation) ; – Fgetss ; – get_magic_quotes_gpc ; – hebrevc (sans dépréciation) ; – money_format ; – restore_include_path (sans dépréciation).
  • 41.
  • 42.
    @hellosct1 – Programmez#10 - Compilateur JIT ● JIT = Just In Time → Compilation à la volée ● Résultat attendu : → Amélioration du langage au niveau vitesse ● Technique – Le JIT traduit ● Les parties extrêmes du code intermédiaire en code machine. – Compiler des parties du code au moment de l'exécution ● Permettre d’utiliser la version compilée à la place
  • 43.
    @hellosct1 – Programmez#10 - Compilateur JIT : configuration ● Développeur – Aucune action à faire ● Administrateur du serveur – modifier dans le fichier de configuration ● Activer ou non certains paramètres : – Modifier la taille du cache, – Ajuster certains Triggers (déclencheurs). https://wiki.php.net/rfc/jit
  • 44.
    @hellosct1 – Programmez#10 - Performance : compilateur JIT https://gist.github.com/PedroEscudero/b64ea7409c0cc483c44f0773b6aebbdb
  • 45.
    @hellosct1 – Programmez#10 - Les autres améliorations ● RFC : https://wiki.php.net/rfc#php_80 ● Union types JIT The nullsafe operator Named arguments Attributes Match expression Constructor property promotion New static return type New mixed type Throw expression Inheritance with private methods Weak maps Allowing ::class on objects Non-capturing catches Trailing comma in parameter lists Create DateTime objects from interface New Stringable interface New str_contains() function New str_starts_with() and str_ends_with() functions New fdiv() function New get_debug_type() function New get_resource_id() function Abstract methods in traits improvements Object implementation of token_get_all() Variable syntax tweaks Type annotations for internal functions ext-json always available * changement Rupture Consistent type errors Reclassified engine warnings The @ operator no longer silences fatal errors Default error reporting level Default PDO error mode Concatenation precedence Stricter type checks for arithmetic and bitwise operators Namespaced names being a single token Saner numeric strings Saner string to number comparisons Reflection method signature changes Stable sorting Fatal error for incompatible method signatures
  • 46.
    @hellosct1 – Programmez#10 - Article complet prochainement
  • 47.
    @hellosct1 – Programmez#10 - Merci Christophe Villeneuve @hellosct1 @hellosct1@mamot.fr