What’s New In PHP 8.1

Enumerations

class Blog
{
const TYPES = [
'BLOG' => 1,
'PAGE' => 2,
'CUSTOM' => 3,
];
}
enum BlogTypes
{
case Blog;
case Page;
case Custom;
}
function validateBlogType(BlogTypes $blogTypes)
{
//
}

$value = BlogTypes:Blog;

validateBlogType($value); // valid method call

validateBlogType('Blog'); // This to return Error of $blogTypes must be of type BlogTypes
echo BlogTypes::Blog; // Prints "Blog"
enum BlogTypes
{
case Blog;
case Page;
case Custom;

public function titlePrefix()
{
if ($this === BlogTypes::Page) {
return 'Page - ';
}
return '';
}
}

echo BlogTypes::Blog->titlePrefix(); // return nothing
echo BlogTypes::Page->titlePrefix(); // return Page -
var_dump(BlogTypes::cases());

array(4) {
[0]=>
enum(BlogTypes::Blog)
[1]=>
enum(BlogTypes::Page)
[2]=>
enum(BlogTypes::Custom)
}

Read Only Properties

class BlogData
{
private Status $status;

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

public function getStatus(): Status
{
return $this->status;
}
}
class BlogData
{
public readonly Status $status;

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

Never Return Type

function redirect(string $uri): never {
header('Location: ' . $uri);
exit();
}

First-class Callable Syntax

$foo = [$this, 'foo'];
$foo = $this->foo();

Final Modifier For Class Constants

class Foo
{
public const XX = "foo";
}

class Bar extends Foo
{
public const XX = "bar"; // No error
}
class Foo
{
final public const XX = "foo";
}

class Bar extends Foo
{
public const XX = "bar"; // Fatal error
}

New Initializers

class Service
{
private Logger $logger;

public function __construct(?Logger $logger = null) {
$this->logger = $logger ?? new NullLogger();
}
}
class Service
{
private Logger $logger;

public function __construct(Logger $logger = new NullLogger()) {
$this->logger = $logger;
}
}

--

--

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