5 Things to do to write better PHP

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']
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

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;
}
if ($user->role !== 'admin' || !$user->is_vip) {
return false;
}
return true;

Match Expression

$class = match ($status) {
'completed' => 'success',
'in_progress' => 'warning',
'failed' => 'danger',
};
$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;
}
}
class Customer
{
public function __construct(
private string $name,
private string $address,
private string $phone
) {}
}

--

--

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
Mhd Omar Bahra

Mhd Omar Bahra

I am a Software Engineer interested in Software Architecture and Quality Assurance.