+ 1

Why shouldn't we initialize a variable when we use global in a function & why we can initialize a normal variable in a function?

7th Apr 2017, 2:28 PM
bhavana goud
bhavana goud - avatar
8 Antworten
+ 4
Because you're not declaring it @bhavana goud, you're calling it. When you use the keyword "global" in front of $name in your function, you're just calling that variable and it's value from global scope, this is also why you can't change it like that inside your function. If you want to change $name inside your function then don't put the keyword "global" in front of it.
9th Apr 2017, 2:16 AM
Ghauth Christians
Ghauth Christians - avatar
+ 12
I don't know if I understand your question. Could you add an example?
8th Apr 2017, 6:16 PM
Tashi N
Tashi N - avatar
+ 10
@Gavin First really useful ascii art I see at Q&A ^^
8th Apr 2017, 7:17 PM
Tashi N
Tashi N - avatar
+ 4
From the looks of your profile, I'm assuming you're referring to PHP variable rules. From the programming languages that I know of, PHP's variable scope rule is the only one that confused me too but I understand it enough to explain it better to you so here it goes. Variables, in any language, has at least either local scope or global scope. The general rule for most programming languages is that a function can access global scope variables but not local scope variables that are declared in another function. PHP however, makes it not possible for you to access global scope variables unless you put the "global" keyword in front of the variable first. That's all that there is to it really, just use that "global" keyword in front of the global scope variable you want to access. Example (PHP): Here's a way to picture it PHP main_______________________ l global scope l l $gavin l l function_________ l l l local scope l l l global $gavin l l l $christians l l______________l_________________ l -above, $gavin can only be accessed if you put the "global" keyword in front, else it will be treated as a local scope variable like $christians
8th Apr 2017, 6:53 PM
Ghauth Christians
Ghauth Christians - avatar
+ 3
Hey @Tashi N, do you like my picture representation? 😊
8th Apr 2017, 7:04 PM
Ghauth Christians
Ghauth Christians - avatar
+ 3
@Tashi N thanks 😊
8th Apr 2017, 7:18 PM
Ghauth Christians
Ghauth Christians - avatar
+ 3
Happy I could help @bhavana goud 😊
9th Apr 2017, 2:25 AM
Ghauth Christians
Ghauth Christians - avatar
+ 2
Thank you @Gavin Christians. Got the clarity. I've been thinking global as a declaration of scope to variable.But now understood that it's calling from global scope. once again tq
9th Apr 2017, 2:23 AM
bhavana goud
bhavana goud - avatar