在 Moodle 中以编程方式找出登录用户的角色,即使用户将登录更改为

In Moodle find out programmatically the role of logged in user even if user changes login as

假设一位老师登录了一门课程,我可以通过编程找出登录用户的角色是老师,没问题

global $USER;
$context = context_course::instance($COURSE->id);
$roles = get_user_roles($context, $USER->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;

假设老师选择LOG IN AS a STUDENT,我如何根据登录用户id找出登录用户的当前角色,因为它总是显示为TEACHER而不是STUDENT?

基本上,如果教师以学生身份登录,如何找出登录用户的角色 "logged in as"

任何帮助将不胜感激

谢谢

if (!empty($_SESSION['USER']->realuser)) {
    // Logged in as.
    $roles = get_user_roles($context, $_SESSION['USER']->realuser, false);
}