3

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() ?>
...
germanfr
  • 547
  • 5
  • 19
  • 1
    They use namespaces and have a variable naming guide. – Jay Blanchard Feb 20 '20 at 15:14
  • @JayBlanchard Variables cannot be namespaced: https://stackoverflow.com/a/5287362/5243770 – germanfr Feb 20 '20 at 15:17
  • 1
    I'd say that most people avoid using the same variable names, if you used an MVC structure you'd find it a lot easier to avoid overwriting variables because most of them would be bound to a class/method scope, it's not an issue I've had major concerns with in the past. I'd say in this scenario the best thing to do would be to rename either `$user` in your example, or `$user` in `includes/headerbar.php` to something more meaningful. – Mark Feb 20 '20 at 15:22
  • 1
    The answer to the question in the title is very simple: **do not use global variables**. Also, do put code at the global level in the included files (let them contain only functions and classes) and, very important, do not mix PHP with HTML. – axiac Feb 20 '20 at 15:45
  • @axiac that doesn't help. I don't know where could I store my user then. – germanfr Feb 20 '20 at 15:54
  • Have a look at MVC methodology, you need controllers to send the $user into views. – Cyrus Feb 20 '20 at 16:00

0 Answers0