interface I {
// We may naively assume that the PHP constant is always a string.
const PHP = 'PHP 8.2';
}
class Foo implements I {
// But implementing classes may define it as an array.
const PHP = [];
}interface I {
const string PHP = 'PHP 8.3';
}
class Foo implements I {
const string PHP = [];
}
// Fatal error: Cannot use array as value for class constant
// Foo::PHP of type stringclass Foo {
const PHP = 'PHP 8.2';
}
$searchableConstant = 'PHP';
var_dump(constant(Foo::class . "::{$searchableConstant}"));class Foo {
const PHP = 'PHP 8.3';
}
$searchableConstant = 'PHP';
var_dump(Foo::{$searchableConstant});#[\Override] RFC
use PHPUnit\Framework\TestCase;
final class MyTest extends TestCase {
protected $logFile;
protected function setUp(): void {
$this->logFile = fopen('/tmp/logfile', 'w');
}
protected function taerDown(): void {
fclose($this->logFile);
unlink('/tmp/logfile');
}
}
// The log file will never be removed, because the
// method name was mistyped (taerDown vs tearDown).use PHPUnit\Framework\TestCase;
final class MyTest extends TestCase {
protected $logFile;
protected function setUp(): void {
$this->logFile = fopen('/tmp/logfile', 'w');
}
#[\Override]
protected function taerDown(): void {
fclose($this->logFile);
unlink('/tmp/logfile');
}
}
// Fatal error: MyTest::taerDown() has #[\Override] attribute,
// but no matching parent method exists#[\Override] a um método, o PHP garantirá que um método com o mesmo nome exista em uma classe pai ou em uma interface implementada. Adicionar o atributo torna claro que a sobreposição de um método pai é intencional e simplifica a refatoração, pois a remoção de um método pai sobreposto será detectada. class PHP {
public string $version = '8.2';
}
readonly class Foo {
public function __construct(
public PHP $php
) {}
public function __clone(): void {
$this->php = clone $this->php;
}
}
$instance = new Foo(new PHP());
$cloned = clone $instance;
// Fatal error: Cannot modify readonly property Foo::$phpclass PHP {
public string $version = '8.2';
}
readonly class Foo {
public function __construct(
public PHP $php
) {}
public function __clone(): void {
$this->php = clone $this->php;
}
}
$instance = new Foo(new PHP());
$cloned = clone $instance;
$cloned->php->version = '8.3';readonly agora podem ser modificadas uma vez dentro do método mágico __clone para permitir a clonagem profunda de propriedades somente leitura. json_validate() RFC
Doc
function json_validate(string $string): bool {
json_decode($string);
return json_last_error() === JSON_ERROR_NONE;
}
var_dump(json_validate('{ "test": { "foo": "bar" } }')); // truevar_dump(json_validate('{ "test": { "foo": "bar" } }')); // truejson_validate() permite verificar se uma string é sintaticamente válida em JSON, sendo mais eficiente do que json_decode(). Randomizer::getBytesFromString() RFC
Doc
// This function needs to be manually implemented.
function getBytesFromString(string $string, int $length) {
$stringLength = strlen($string);
$result = '';
for ($i = 0; $i < $length; $i++) {
// random_int is not seedable for testing, but secure.
$result .= $string[random_int(0, $stringLength - 1)];
}
return $result;
}
$randomDomain = sprintf(
"%s.example.com",
getBytesFromString(
'abcdefghijklmnopqrstuvwxyz0123456789',
16,
),
);
echo $randomDomain;// A \Random\Engine may be passed for seeding,
// the default is the secure engine.
$randomizer = new \Random\Randomizer();
$randomDomain = sprintf(
"%s.example.com",
$randomizer->getBytesFromString(
'abcdefghijklmnopqrstuvwxyz0123456789',
16,
),
);
echo $randomDomain;Randomizer::getFloat() e Randomizer::nextFloat() RFC
Doc
// Returns a random float between $min and $max, both including.
function getFloat(float $min, float $max) {
// This algorithm is biased for specific inputs and may
// return values outside the given range. This is impossible
// to work around in userland.
$offset = random_int(0, PHP_INT_MAX) / PHP_INT_MAX;
return $offset * ($max - $min) + $min;
}
$temperature = getFloat(-89.2, 56.7);
$chanceForTrue = 0.1;
// getFloat(0, 1) might return the upper bound, i.e. 1,
// introducing a small bias.
$myBoolean = getFloat(0, 1) < $chanceForTrue;$randomizer = new \Random\Randomizer();
$temperature = $randomizer->getFloat(
-89.2,
56.7,
\Random\IntervalBoundary::ClosedClosed,
);
$chanceForTrue = 0.1;
// Randomizer::nextFloat() is equivalent to
// Randomizer::getFloat(0, 1, \Random\IntervalBoundary::ClosedOpen).
// The upper bound, i.e. 1, will not be returned.
$myBoolean = $randomizer->nextFloat() < $chanceForTrue;Devido à precisão limitada e ao arredondamento implícito de números de ponto flutuante, gerar um float imparcial dentro de um intervalo específico não é trivial, e as soluções comumente usadas no nível do usuário podem gerar resultados tendenciosos ou números fora do intervalo solicitado.
O Randomizer também foi ampliado com dois métodos para gerar floats de maneira imparcial. O método Randomizer::getFloat() utiliza o algoritmo da seção γ que foi publicado em Drawing Random Floating-Point Numbers from an Interval. Frédéric Goualard, ACM Trans. Model. Comput. Simul., 32:3, 2022.
php -l foo.php bar.php
No syntax errors detected in foo.php
php -l foo.php bar.php
No syntax errors detected in foo.php
No syntax errors detected in bar.php
O linter da linha de comando agora aceita vários nomes de arquivos para lint
DOMElement::getAttributeNames(), DOMElement::insertAdjacentElement(), DOMElement::insertAdjacentText(), DOMElement::toggleAttribute(), DOMNode::contains(), DOMNode::getRootNode(), DOMNode::isEqualNode(), DOMNameSpaceNode::contains() e DOMParentNode::replaceChildren().IntlCalendar::setDate(), IntlCalendar::setDateTime(), IntlGregorianCalendar::createFromDate() e IntlGregorianCalendar::createFromDateTime().ldap_connect_wallet() e ldap_exop_sync().mb_str_pad().posix_sysconf(), posix_pathconf(), posix_fpathconf() e posix_eaccess().ReflectionMethod::createFromMethodName().socket_atmark().str_increment(), str_decrement() e stream_context_set_options().ZipArchive::getArchiveFlag().zend.max_allowed_stack_size para definir o tamanho máximo permitido da pilha.n a um array vazio agora garantirá que o próximo índice seja n + 1 em vez de 0.range().U_MULTIPLE_DECIMAL_SEPERATORS foi obsoleta em favor de U_MULTIPLE_DECIMAL_SEPARATORS.MT_RAND_PHP do Mt19937 está obsoleta.ReflectionClass::getStaticProperties() não será mais nulo.assert.active, assert.bail, assert.callback, assert.exception e assert.warning foram obsoletas.get_class() e get_parent_class() sem argumentos está obsoleto.