5 Things to do to write better PHP
This article is based on php8.1 and newer
Isset and Empty
We all need to check for isset or empty in our php code but I’ve seen many people who misuse them, i.e
if (isset($_POST['name']) && !empty($_POST['name']))
$name = $_POST['name']
there’s nothing wrong with the above example, but it can be simplified to
if (!empty($_POST['name']))
$name = $_POST['name']
Null Safe Operator
We all need to check for null, sometimes we use isset or empty as shown above. A better and a more readable approach which we can use sometimes would be this
$name = $_POST['name'] ?? null
there’re many forms and ways to use the null safe operator, a very well written article by Brent Roose will show you, null safe operators, in detail.
Guard Conditionals
We all use conditionals to comply with certain constraints, however, using if-else a lot in the code would lead to a very horrible and messy code such as the code below
if ($user->role == 'admin') {
if (user->is_vip == true) {
return true;
}
else {
return false;
}
} else {
return false;
}
A better way to type the above constraint would be
if ($user->role !== 'admin' || !$user->is_vip) {
return false;
}return true;
Match Expression
$class = match ($status) {
'completed' => 'success',
'in_progress' => 'warning',
'failed' => 'danger',
};
The typical way using switch would be
$class = null;
switch ($status) {
case 'completed':
$class = 'success';
break;
case 'in_progress':
$class = 'warning';
break;
case 'failed':
$class = 'danger';
break;
}
Property Promotion
Typical Approach
class Customer
{
private string $name;
private string $address;
private string $phone;
public function __construct(string $name, string $address, string $phone)
{
$this->name = $name;
$this->address = $address;
$this->phone = $phone;
}
}
Using Property Promotion
class Customer
{
public function __construct(
private string $name,
private string $address,
private string $phone
) {}
}
I hope you enjoyed reading this article.