Asymmetric Property Visibility in PHP 8.4


PHP 8.4 is scheduled to be released tomorrow, and one exciting feature we haven't covered yet is Asymmetric Property Visibility. Starting in PHP 8.4, properties may also have their visibility set asymmetrically with a different scope for reading and writing. Here's an example from the documentation:
class Book
{
public function __construct(
public private(set) string $title,
public protected(set) string $author,
protected private(set) int $pubYear,
) {}
}

class SpecialBook extends Book
{
public function update(string $author, int $year): void
{
$this->author = $author; // OK
$this->pubYear = $year; // Fatal Error
}
}

$b = new Book('How to PHP', 'Peter H. Peterson', 2024);

echo $b->title; // How to PHP
echo $b->author; // Peter H. Peterson
echo $b->pubYear; // Fatal Error

Providing public access to a property but preventing a (set) publicly is illustrated in how both $title and $author can be accessed publicly. However, you can see granular control is how these properties can be set (protected or private). Class properties must have a type to set a separate visiblity, and set must be the same or more restrictive than get.
Follow our PHP 8.4 post to get updates as PHP 8.4 is released on November 21st!

The post Asymmetric Property Visibility in PHP 8.4 appeared first on Laravel News.
Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.