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 trialChristopher Eastridge
3,819 PointsPurpose of redefining a variable.
I have seen many explanations of how you can recall and modify arrays and I always wonder the same thing. Is there any specific reason you would want to redefine a variable after it has already been declared? Example such as redefining the color green to hazel. Why wouldn't you just delete or change the color green directly to reflect hazel? Is this just to show the cascading nature of PHP or is there a more valuable purpose?
syriaca
3,742 PointsI will repeat what have been said by Cena Mayo 5 months ago (but it maybe will help me to never forget it too) :
VARIABLES = are for variable content, CONSTANT = are for limited or never changing content.
For me, PHP have been designed to deserve dynamic content, not static content. It sounds pretty legit to think it is a more variable related language than simple HTML.
1 Answer
Stone Preston
42,016 Pointsthe ability to change after already being declared IS the whole purpose of a variable. thats what makes them variables. if you have a variable that never changes (such as a color or something) it should probably be a constant.
lets say you have an array of usernames that you obtain from a database. you can create a variable to store that
$usernames = <some array of usernames>
but then suppose that another user got added to the backend. you would want to update that usernames variable so that it contains the new value. so you reassign it a value
$usernames = <new array of usernames>
Why wouldn't you just delete or change the color green directly to reflect hazel?
because most of the time variables need to change when the program is running. you cant modify it directly (ie delete the old value, then type in the new value) if its running
Cena Mayo
55,236 PointsCena Mayo
55,236 PointsThis isn't intended as a definitive statement as I am also a PHP newbie, but by their definition, variables are intended to change value. (That's why they're not constants. :))
So for example, you might declare $color = green by default (global variable), but within the context of a specific function(local variable) - a button is clicked, say - you might change $color = red for the duration of that event. Once the function is executed and exited, $color would once again = green.