Array to string conversion error in PHP 7.2 when returning user role as class

This code works and is perfectly valid, running on 7.3, except when your user has two roles:

add_filter( 'body_class', function( $classes="" ) {
    $current_user   = new \WP_User(get_current_user_id());
    $user_role      = ['administrator', 'moderator']; //just a test, but this is what it'll look like if it had 2 roles.
    $classes        = [];
    $classes[]      = 'role-' . $user_role;
    return $classes;
});

Then, what do you know, the same error appears. Also, you’re passing a string as $classes to your anonymous function, where-as the filter clearly demands an array.

Do this instead:

add_filter( 'body_class', function( $classes ) {
    $current_user = wp_get_current_user();

    foreach( $current_user->roles as $user_role ) {
        $classes[] = 'role-' . $user_role;
    }
    return $classes;
});