I'm not entirely sure if this is possible in Java, but how would I use a string declared in an if-statement outside of the if-statement it was declared in?
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
Right now $uname is only in scope within the if statement, once you leave the if statement the variable no longer exists. PHP has no block scope for variables, so they are available until the end of the function once they have been assigned a value.
Yes. It is also true for for scope.
If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class. class Geek: # Variable defined inside the class.
You can't because of variable scope.
If you define the variable inside an if
statement, than it'll only be visible inside the scope of the if
statement, which includes the statement itself plus child statements.
if(...){
String a = "ok";
// a is visible inside this scope, for instance
if(a.contains("xyz")){
a = "foo";
}
}
You should define the variable outside the scope and then update its value inside the if
statement.
String a = "ok";
if(...){
a = "foo";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With