Asymmetric Property Visibility in PHP 8.4
Last updated on by Paul Redmond
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 PHPecho $b->author; // Peter H. Petersonecho $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!