PHP 8.4 Course in Practice – What New Features Does PHP 8.4 Introduce?
PHP 8.4, released on November 21, 2024, brings a series of innovations that significantly impact web application development. Among them are Property Hooks, Asymmetric Visibility, new array functions, and HTML5 support. These changes not only facilitate daily work for programmers but also provide a solid foundation for creating your own PHP frameworks.
Property Hooks – A New Dimension of Property Control
Thanks to Property Hooks, we can define getter and setter behavior without the need to write additional methods. This solution allows for cleaner and more concise code.
PHP 8.4
<?php
class Locale
{
public string $locale
{
get => $this->first . "_" . $this->second;
set (string $value) {
[$this->first, $this->second] = explode("_", $value);
}
}
public function __construct(
private string $first,
private string $second
){}
}
PHP 8.3
<?php
class Locale
{
public function __construct(
private string $first,
private string $second
) {}
public function getLocale(): string
{
return $this->first . "_" . $this->second;
}
public function setLocale(string $value)
{
[$this->first, $this->second] = explode("_", $value);
}
}
Asymmetric Visibility – Precise Access Control
This new functionality allows for differentiating access levels to properties – for example, public read and private write. This is an ideal solution for framework creators who want to ensure security and flexibility.
PHP 8.4
<?php
class Car
{
public function __construct(
public private(set) string $color,
) { }
public function paint(string $color)
{
$this->color = $color;
}
}
$car = new Car("red");
$car->paint("blue");
echo $car->color; //red
PHP 8.3
<?php
class Car
{
public function __construct(
public string $color,
) { }
public function paint(string $color): void
{
$this->color = $color;
}
public function getColor(): string
{
return $this->color;
}
}
$car = new Car("red");
$car->paint("blue");
echo $car->getColor(); //allowed, red
Want to see more practical examples? Download free ebook sample 📥 or Buy PHP course 🎓
New Array Functions – Easier Data Manipulation
Functions like array_find
, array_find_key
, array_any
, and array_all
facilitate array manipulation, which is invaluable when creating dynamic framework components.
PHP 8.4
<?php
$data = [1,2,3,5,7,9];
$x = array_find($data, fn(int $val) => $val > 5);//7
$any = array_any($data, fn(int $val) => $val >=9 );//true
PHP 8.3
<?php
$data = [1,2,3,5,7,9];
$x = null;
foreach ($data as $val)
{
if($val > 5) {
$x = $val;
break;
}
}
$any = false;
foreach ($data as $val)
{
if($val >=9) {
$any = true;
break;
}
}