public static function instance($courseorid, $userid = 0) {
        global $USER;
        if (is_object($courseorid)) {
            $course = $courseorid;
        } else {
            $course = (object)array('id' => $courseorid);
        }
        if (empty($userid)) {
            $userid = $USER->id;
        }

        if (!empty(self::$instancecache[$course->id])) {
            if (self::$instancecache[$course->id]->userid == $userid &&
                    (!isset($course->cacherev) ||
                    $course->cacherev == self::$instancecache[$course->id]->get_course()->cacherev)) {
                // This course's modinfo for the same user was recently retrieved, return cached.
                self::$cacheaccessed[$course->id] = microtime(true);
                return self::$instancecache[$course->id];
            } else {
                // Prevent potential reference problems when switching users.
                self::clear_instance_cache($course->id);
            }
        }
        $modinfo = new course_modinfo($course, $userid);

        // We have a limit of MAX_MODINFO_CACHE_SIZE entries to store in static variable.
        if (count(self::$instancecache) >= MAX_MODINFO_CACHE_SIZE) {
            // Find the course that was the least recently accessed.
            asort(self::$cacheaccessed, SORT_NUMERIC);
            $courseidtoremove = key(array_reverse(self::$cacheaccessed, true));
            self::clear_instance_cache($courseidtoremove);
        }

        // Add modinfo to the static cache.
        self::$instancecache[$course->id] = $modinfo;
        self::$cacheaccessed[$course->id] = microtime(true);

        return $modinfo;
    }