Jump to content

scope and global


Caitlin-havener
 Share

Recommended Posts

Now I tried to figure this out with dreamweaver but it keeps throwing an error. I wonder if my professors question was worded incorrectly. He doesn't say to call the function in the main program. What would $x print out?

print $x;		function something(){		global $x = 5;	}

Link to comment
Share on other sites

If $x was previously assigned a value, or if something() was called previously in the file, the print would output whatever value $x has. In the case of something(), that would be the value 5.As it stands though, the only expected result is a notice of an undefined variable, which is the message I suppose you're getting.The answer of the question is probably "an empty string", because that's what happens when you try to print an undefined variable - it gets defined with the value null which in turn is printed out as an empty string.

Link to comment
Share on other sites

K thats what I thought it just seemed like a weird question. So does global only work like you state global in the function and it takes the value from outside the function? It doesn't take a value from within a function and send it out to the main program (unless the function is called of course)?

Link to comment
Share on other sites

It works both ways. The variable from the global scope with the same name is available within the function for both reading and writing. If written to, the global scope will have the newly written value.Without actually running the something() function though, you're never doing the writing. You're just expressing your intention on doing it, should the function be called.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...