Assigning variable defaults in PHP

It’d be nice if PHP had a quick Or-Equals expression like Ruby:

user ||= User.new

but we make do with few slightly less sugary idioms.

The standard way

if (isset($user)) {
  $user = new User();
}

A bit shorter

$user = isset($user) ? $user : new User();

Shorter still

This is my preferred way of making sure variables are set. Short and clear.

isset($user) || $user = new User();

Expressions with defaults

It’s usually best not to treat variable assignments as booleans but in cases like this I think it’s clear enough what’s happening.

($user = $request->getUser()) || $user = new User();
Published
Categorized as PHP

Leave a Comment