For coders TYPO3 Tech Corner

Null-Safe Operator in the TYPO3 area

Null-Safe Operator in the TYPO3 area

In PHP, you're sure to come across variables that don't contain an expected object or arrays that don't have a certain key set. Various IF conditions may also have been inserted. Here are a few examples of how you can write smart code using a null-save operator.

PHP

Here is a short example of arrays:

# Old $color = ''; if (array_key_exists('color', $this->settings)) { $color = $this->settings['color']; } # New $color = $this->settings['color'] ?? '';

And here for function and property calls:

# Old $address = $customer->getAddress(); $country = null; if ($address->getCountry() !== null) { $country = $address->getCountry(); } # Not quite so old $address = $customer->getAddress(); $country = $address ? $address->getCountry() : null; # New $country = $customer->getAddress()?->getCountry(); # Alternative example $tsfe = $GLOBALS['TSFE'] ?? null; $id = (int)$tsfe?->id;
TypoScript

The topic has also already arrived in TypoScript. Problems can quickly arise, especially when using conditions. Here is an example when $GLOBALS['TSFE'] is not available (e.g. in the backend or CLI context):

# Old [getTSFE().type == 123] # New [getTSFE()?.type == 123]
JavaScript

We have one more. In JavaScript you can also avoid unnecessary IF conditions with a null-save operator:

# Old let myValue = ''; const element = document.querySelector('[data-foo]'); if (element !== null) { myValue = element. getAttribute('data-foo'); } # New let myValue = document.querySelector('[data-foo]')?.getAttribute('data-foo');

Back

"Code faster, look at the time" - does this sound familiar to you?

How about time and respect for code quality? Working in a team? Automated tests?

Join us