A variable declared outside of a function will not be available inside of a function, unless be declare it inside the function with the global command.
Anyway, the below serves as a personal reminder.
If we take $loggedIn for example, this would not work when the function is called if we didn't have the global $loggedIn statement, unlike the Python and Java examples for reference below.
<?php
$loggedIn=True;
function setLoginIcon()
{
global $loggedIn;
if ($loggedIn)
{
echo 'True';
}
else
{
echo 'False';
}
}
?>
Also note that declaring a variable static inside a function will make it available outside the function.
As an example of how, say Python is different, see below;
a = True
def myFunction():
if (a):
print("True")
else:
print("False")
myFunction()
Similarly, see below for a Java example;
public class JavaApplication20
{
boolean a = true;
public void myFunction()
{
if (a)
{
System.out.println("True");
}
else
{
System.out.println("False");
}
}
public static void main(String[] args)
{
JavaApplication20 a = new JavaApplication20();
a.myFunction();
}
}
On another note, scope for local variables should generally be considered to be within the bounds of which is was created/declared, see the following example in C;
#include <stdio.h>
int main()
{
int a=5; // local var a set to 5
printf("I'm a local: %d addr: %d\n", a, &a);
if (1)
{
// We'll always run...
int a=10; // local var a set to 10
printf("I'm also a local: %d addr: %d\n", a, &a);
}
// which local var will we print here...
printf("finally, %d addr: %d", a, &a);
return 0;
}
In the above we see that the address of the variable inside the if statement is different from the other.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.