Enumerations RFC Doc
PHP < 8.1
class Status
{
const DRAFT = 'draft';
const PUBLISHED = 'published';
const ARCHIVED = 'archived';
}
function acceptStatus[string $status] {...}
PHP 8.1
enum Status
{
case Draft;
case Published;
case Archived;
}
function acceptStatus[Status $status] {...}
Use enum instead of a set of constants and get validation out of the box.
Readonly Properties RFC Doc
PHP < 8.1
class BlogData
{
private Status $status;
public function
__construct[Status $status]
{
$this->status = $status;
} public function
getStatus[]: Status
{
return $this->status;
}
}
PHP 8.1
class BlogData
{
public readonly Status $status;
public function
__construct[Status $status]
{
$this->status = $status;
}
}
Readonly properties cannot be changed after initialization, i.e. after a value is assigned to them.
They are a great way to model value objects and
data-transfer objects.
First-class Callable Syntax RFC Doc
PHP < 8.1
$foo = [$this, 'foo'];$fn = Closure::fromCallable['strlen'];
PHP 8.1
$foo = $this->foo[...];$fn = strlen[...];
It is now possible to get a reference to any function – this is called first-class callable syntax.
New in initializers RFC
PHP < 8.1
class Service
{
private Logger $logger;
public function
__construct[
?Logger $logger = null,
] {
$this->logger = $logger ?? new NullLogger[];
}
}
PHP 8.1
class Service
{
private Logger $logger;
public function
__construct[
Logger $logger = new NullLogger[],
] {
$this->logger = $logger;
}
}
Objects can now be used as default parameter values, static variables, and global constants, as well as in attribute arguments.
This effectively makes it possible to use nested attributes.
PHP < 8.1
class User
{
/**
* @Assert\All[{
* @Assert\NotNull,
* @Assert\Length[min=5]
* }]
*/
public string $name = '';
}
PHP 8.1
class User
{
#[\Assert\All[
new \Assert\NotNull,
new \Assert\Length[min: 5]]
]
public string $name = '';
}
Pure Intersection Types RFC Doc
PHP < 8.1
function count_and_iterate[Iterator $value] {
if [![$value instanceof Countable]] {
throw new TypeError['value must be Countable'];
}
foreach [
$value as $val] {
echo $val;
}count[$value];
}
PHP 8.1
function count_and_iterate[Iterator&Countable $value] {
foreach [$value as $val] {
echo $val;
}count[$value];
}
Use intersection types when a value needs to satisfy multiple type constraints at the same time.
It is not currently possible to mix intersection and union types together such as A&B|C
.
Never return type RFC Doc
PHP < 8.1
function redirect[string $uri] {
header['Location: ' . $uri];
exit[];
}
function
redirectToLoginPage[] {
redirect['/login'];
echo 'Hello'; //