get_posts() and global variables

get_posts doesn’t modify global variables & is safe to use anywhere but setup_postdata does modify the global variables.

Use the function wp_reset_postdata() just after the foreach loop. It reverses the changes made by setup_postdata. The thing it does is basically same as you did in your example, you just won’t need to worry about the temporary variable.