Variable Scope
Basics
A variable is only usable within the scope (i.e. section of code) that it was defined in.
// Scope A { $someVar = 'abc' print($someVar) // ✓ OK } // Scope B { print($someVar) // ✕ ERROR }
This has a couple of benefits:
1. If a variable elsewhere in your code coincidentally has the same name, there is no risk that it will be overwritten.
2. It takes less mental effort, because at any given time, you only need to think about the variables in the current scope.
Block Scope
A block is generally any code within a set of curly braces {...}
. (e.g. if
statements, function bodies, etc.)
Variables can only be accessed in the block that they were defined in, including any inner blocks.
if ... { $outerVar = 123 if ... { print($outerVar) // ✓ OK } }
Variables defined in inner blocks are NOT available in outer blocks.
if ... { if ... { $innerVar = 123 } print($innerVar) // ✕ ERROR }
Function Scope
Variables that are defined within a function are NOT available outside that function.
fun commandA { $varA = 123 } fun commandB { print($varA) // ✕ ERROR }
Likewise, variables outside of functions are not available inside a function.
$outerVar = 123 fun doSomething { print($outerVar) // ✕ ERROR }
Note: Closures are an exception to this rule.