Undefined Variable since PHP 8.0

Hey all,

The code bellow worked for quite some time, but after changing the php version to 8.0,
I get the error 'undefined variable on ‘$os’ and many other parts of my code.
What can this be?

<?php
$detect = new Mobile_Detect;
// CHECK DEVICE
if ($detect->isMobile() && !$detect->isTablet()) {
    $device = "device-is-mobile";
} elseif ($detect->isTablet()) {
    $device = "device-is-tablet";
} else {
    $device = "device-is-desktop";
}

// CHECK OS
if ($detect->isIphone()) {
    $os = "os-is-iphone";
} elseif ($detect->isSamsung()) {
    $os = "os-is-samsung";
}

//CHECK BROWSER
if ($detect->isChrome()) {
    $browser = "browser-is-chrome";
} elseif ($detect->isSafari()) {
    $browser = "browser-is-safari";
}

?>

<!DOCTYPE html>
<html lang="nl" class="<?= $device ?><?= ' ' . $os ?><?= ' ' . $browser ?>">

That’s because if none of your two conditions is true, $os is not defined. You need to set it to a default value at the outset.

Hi Moonwalk, thanks for your input. Your solution does work.
I use this logic in many places. I am wondering why I get all these errors now, and not before.
I also set the php version back to an earlier one, but it doesnt do the trick.
Any ideas there?

It looks like this does not work anymore:

if($object) { }

Is that correct? What is the equivalent that works??

What is $object, without any context, we cannot tell what’s wrong.

That is just an abstract example, because I use it many times. Now its raining errors in my site :frowning:

When you type

If($os) {}

It will now give an error if $os doesn’t exist.
Th same with:

<?= $os ?>

It didnt throw an error in php 7.4 / Kirby 3.7
I didnt see it between the list changes of Kirby 3.8?
When I update to php 8 and kirby 3.8 It throws the error. Any ideas?

It works as an equivalent of isset($object) I just learned.

Should I change this everywhere now?

PHP 8.0 is a lot stricter than PHP 7.4. You should never have any undefined variables. It says in the changelog that you need to change your template code to make it compatible with PHP 8+.

yes.

just to be clear, trying to access an undefined variable was also “wrong” in PHP 7, it generated an error message at the “NOTICE” level. In PHP 8 it now generates a “WARNING”; also the default error reporting level in PHP 8 has been set to “E_ALL”, while, before, by default it wouldn’t show "NOTICE"s.

Anyway, I guess you can choose between always setting a variable before using it (The Right Way™), or just provide a fallback value via the null coalescing operator when accessing the variable:

<?php
if($os ?? null) {
  //stuff
}
?>

<?= $os ?? null ?>

Thanks everyone! The context is now clear as well as the way forward. :dizzy: