Best way to give a variable a default value (simulate Perl ||, ||= )

The best way to give a variable a default value in PHP is to use the ternary operator ?:. This operator allows you to assign a value to a variable based on a conditional statement. For example:

<?php

$var = isset($var) ? $var : 'default value';

echo $var;

This line of code checks if the variable $var is set, and if it is, it assigns its value to $var. If it is not set, it assigns the string 'default value' to $var.

Watch a course Learn object oriented PHP

Another way is to use the null coalesce operator (??) in PHP 7 or later:

<?php

$var = $var ?? 'default value';

echo $var;

This operator checks if the variable on the left is defined and not null, if it's not it will take the value on the right.