Page 41 - Open Soource Technologies 304.indd
P. 41
Unit 2: Language Basics
They are represented by adding an additional dollar sign in front of the variable so that the name Notes
gets parsed twice.
$foo_bar = “abc”;
$tip = “foo_bar”;
echo $tip; // writes out ‘foo_bar’
echo $$tip // writes out ‘abc’
Sometimes curly brackets are used to make the code a little clearer. Curly brackets, in PHP, are
grouping elements. By using them with a variable name, you can make it clear what each dollar
sign is acting on in the variable name. This makes the code easier to read.
$$tip // harder to read
${$tip} // easier to read
2.3.3 Variable Scope
All variables have scope. The scope of a variable is the portion of the script in which the variable
can be referenced. PHP has four different variable scopes.
• Local
• Global
• Static
• Parameter
In PHP, all variables are local in scope, even the global ones.
Local Scope
A local variable is on that is specific to a given instance of a given function. It is created when the
function processing begins and is deleted as soon as the function is completed.
Local scope is specific to functions. PHP does not have a block level scope. If you want a block
level scope, your best bet is to emulate it with a recursive function.
Global Scope
Global scope refers to any variable that is defined outside of any function. They can be accessed
from any part of the program that is not inside a function.
To access a global variable from within a function, you can call it into the function with the global
keyword:
global $varToInclude;
PHP also stores all global variables in an array called $GLOBALS[ ]. Its index is the name of the
variable. This array is accessible from within functions and can be used to update global variables
directly.
global $somVar;
$someVar = ‘abc’
// is the same as
$GLOBALS [“someVar”] = ‘abc’;
LOVELY PROFESSIONAL UNIVERSITY 35