I am creating a PHP application which has many pages that show a resource depending on a get parameter, for example a user profile page.
First I query the database for that resource, and then I use the object to show its information across the page. The problem is that there are some includes or functions that are overriding the same variable, and when I reach the end of the page it's changed.
There are many other questions about this in SO with a simple "use classes to avoid polluting your global namespace", but after all you have to have at least one reference to your data somewhere. I'd like to know if there is any proper way to prevent included files from overriding global variables, or if there is any alternative that grants my variable is safe. What do people do with this problem in big proyects?
This is a simplified example of my problem:
<?php
$user = User::get_user_by_id($conn, $id); // returns an instance of User class
?>
<html>
<title><?php echo $user->fullname() ?>'s profile</title>
...
<?php include REAL_APP_ROOT.'/includes/headerbar.php'; ?>
<!-- At this point $user has a different value -->
...
<!-- Oops: wrong information below -->
<img src="<?php echo $user->avatar() ?>"/> <span><?php echo $user->fullname() ?>
...