Variables, Misc
Command-line arguments
$argv // $argv[0]: script name; $argv[1]: first parameter, ...
Scalars
- Booleans, integers, floating point
numbers, strings.
NULL
- To specify a literal NULL value, use
the keyword NULL, which
is case insensitive.
- Don't compare a variable to the keyword
NULL (zero values
cause it to misfire); use
is_null() instead.
- It's been assigned the constant NULL.
- It hasn't been set to any value yet.
- It's been
unset().
Variable scope
- By default, variables declared within a function are local
- Global variables must be
declared global inside a
function, using the keyword "
global", if they are going to
be used in
that function.
- Global variables can also be accessed
using the
$GLOBALS
associative array.
function Sum() {
global $a, $b;
...
$GLOBALS["c"] = $a;
$x = $GLOBALS["c"];
}
Variable variables
- The name of variable variables can be
set and used
dynamically.
- A variable variable takes the value of
a variable and treats
that as the name of a variable.
- The indirectly-named variable, when
accessed, will
automatically be created if it does not already exist.
$var = "hello";
$$var = "world"; // Equivalent to: $hello = "world";
echo "$var ${$var}"; // "hello world"
echo "$a $hello"; // "hello world"
${$a[1]} // Use $a[1] as an indirectly-named variable
${$a}[1] // Use $$a as an array variable variable; access the [1] index
Variable parsing
- Used for double-quote strings and
heredoc text.
- Variables can be placed inside curly
braces, to ensure that
they're expanded correctly.
- The
$ character can be
either inside or
outside of the curly
braces.
- Use "
{$" or "\{$"
to get a literal
"{$".
$apple = "apple";
echo "$apple ${apple} {$apple}";
echo "${apple}s {$apple}s";
echo "{$fruits['banana']}";
echo "$rectangle->width {$rectangle->width}";