Wordpress - Upgrade from 5.0.4 to 5.1.1 causes $theme to be null

Since Changeset 44524, which has landed in WordPress 5.1, the variable $theme is now a global variable set by WordPress which also gets unset after the themes have been bootstrapped:

// Load the functions for the active theme, for both parent and child theme if applicable.
foreach ( wp_get_active_and_valid_themes() as $theme ) {
    if ( file_exists( $theme . '/functions.php' ) ) {
        include $theme . '/functions.php';
    }
}
unset( $theme );

This means that any value set by your theme gets also unset.

To fix the fatal error you now have to replace all variables named $theme with a prefixed version, for example $my_theme. Prefixing variables and functions in global scope is considered best practice to avoid such issues.