Lançado!
PHP 8.2 é a grande atualização da linguagem PHP.
Esta atualização inclui muitos novos recursos e otimizações. Classe somente leitura, tipo independente, null, false e true como tipos stand alone, propriedades dinâmicas obsoletas, melhorias de desempenho e muito mais.

Classes somente leitura RFC Doc

PHP < 8.2
class BlogData
{
public readonly
string $title;

public readonly
Status $status;

public function
__construct(string $title, Status $status)
{
$this->title = $title;
$this->status = $status;
}
}
PHP 8.2
readonly class BlogData
{
public
string $title;

public
Status $status;

public function
__construct(string $title, Status $status)
{
$this->title = $title;
$this->status = $status;
}
}

Tipos DNF (Disjunctive Normal Form) RFC Doc

PHP < 8.2
class Foo {
public function
bar(mixed $entity) {
if (((
$entity instanceof A) && ($entity instanceof B)) || ($entity === null)) {
return
$entity;
}

throw new
Exception('Invalid entity');
}
}
PHP 8.2
class Foo {
public function
bar((A&B)|null $entity) {
return
$entity;
}
}
Tipos DNF nos permite união e interseção de tipos, seguindo uma regra estrita: ao combinar tipos de união e interseção, os tipos de interseção devem ser agrupados com colchetes

Permite null, false e true como tipos stand alone RFC RFC

PHP < 8.2
class Falsy
{
public function
almostFalse(): bool { /* ... */ *}

public function
almostTrue(): bool { /* ... */ *}

public function
almostNull(): string|null { /* ... */ *}
}
PHP 8.2
class Falsy
{
public function
alwaysFalse(): false { /* ... */ *}

public function
alwaysTrue(): true { /* ... */ *}

public function
alwaysNull(): null { /* ... */ *}
}

Nova extensão "Random" RFC RFC Doc

PHP 8.2
use Random\Engine\Xoshiro256StarStar;
use
Random\Randomizer;

$blueprintRng = new Xoshiro256StarStar(
hash('sha256', "Example seed that is converted to a 256 Bit string via SHA-256", true)
);

$fibers = [];
for (
$i = 0; $i < 8; $i++) {
$fiberRng = clone $blueprintRng;
// Xoshiro256**'s 'jump()' method moves the blueprint ahead 2**128 steps, as if calling
// 'generate()' 2**128 times, giving the Fiber 2**128 unique values without needing to reseed.
$blueprintRng->jump();

$fibers[] = new Fiber(function () use ($fiberRng, $i): void {
$randomizer = new Randomizer($fiberRng);

echo
"{$i}: " . $randomizer->getInt(0, 100), PHP_EOL;
});
}

// The randomizer will use a CSPRNG by default.
$randomizer = new Randomizer();

// Even though the fibers execute in a random order, they will print the same value
// each time, because each has its own unique instance of the RNG.
$fibers = $randomizer->shuffleArray($fibers);
foreach (
$fibers as $fiber) {
$fiber->start();
}

A extensão "random" fornece uma nova API orientada a objetos para geração de números aleatórios. Em vez de depender de um gerador de números aleatórios globalmente semeado (RNG) usando o algoritmo Mersenne Twister, a API orientada a objetos fornece várias classes ("Engine"s) que fornecem acesso a algoritmos modernos que armazenam seu estado em objetos para permitir várias sequências semeáveis ​​independentes .

A classe \Random\Randomizer fornece uma interface de alto nível para usar a aleatoriedade do mecanismo para gerar um número inteiro aleatório, embaralhar um array ou string, selecionar chaves de array aleatórias e muito mais.

Constantes em Traits RFC Doc

PHP 8.2
trait Foo
{
public const
CONSTANT = 1;
}

class
Bar
{
use
Foo;
}

var_dump(Bar::CONSTANT); // 1
var_dump(Foo::CONSTANT); // Error
Você não pode acessar a constante através do nome da Trait, mas você pode acessar a constante através da classe que usa a Trait.

Propriedades dinâmicas obsoletas RFC Doc

PHP < 8.2
class User
{
public
$name;
}

$user = new User();
$user->last_name = 'Doe';

$user = new stdClass();
$user->last_name = 'Doe';
PHP 8.2
class User
{
public
$name;
}

$user = new User();
$user->last_name = 'Doe'; // Deprecated notice

$user = new stdClass();
$user->last_name = 'Doe'; // Still allowed

A criação de propriedades dinâmicas está obsoleta para ajudar a evitar enganos e erros de digitação, a menos que a classe opte por usar o atributo de #[\AllowDynamicProperties]. stdClass permite propriedades dinâmicas.

O uso dos métodos mágicos __get/__set não é afetado por esta alteração.

Alterações obsoletas e incompatíveis

To Top