Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Scope and lifespan of variables in PHP

I have troubles in understanding the scope of variable in PHP. for example: in start.php I define $a = 123; Then following a link the visitor is transferred to end.php Within end.php will be $a defined with the value 123?

On a different context. I have two concurrent users accessing the same web page. Are the two sessions living in completely separated sandboxes?

Now, let's suppose that I am executing a php scrip (example.php). I close the browser window and reopen example.php immediately. Are the variable from the first session still available in the second session?

2 Answers

"... will be $a defined with the value 123?" - short answer no. It actually depends on where you declare $a. If it is a session variable or in a cookie, it actually would be defined in end.php. In general though, a variable doesn't have any scope outside the current execution context. In other words, if you go to start.php, the server runs the script, evaluates variables, expressions, etc., returns the output and then throws everything away. When you go to end.php, that script would be run including anything that was declared in that particular script. The values don't persist between pages. This is why sessions and cookies were developed in the first place.

As for your second question, each request to the server will run in it's own thread, or sandbox, if you like.

Thanks Aaron, that answer perfectly my question.

glad I could help :-)