Page 78 - Open Soource Technologies 304.indd
P. 78
Unit 6: Building Blocks of PHP
6.1.1.1 Indirect References to Variables Notes
An extremely useful feature of PHP is that you can access variables by using indirect references,
or to put it simply, you can create and access variables by name at runtime.
Consider the following example:
$name = ”John”;
$$name = ”Registered user”;
print $John;
This code results in the printing of ”Registered user.” The bold line uses an additional $ to
access the variable with name specified by the value of $name (”John”) and changing its value
to “Registered user”. Therefore, a variable called $John is created. You can use as many levels
of indirections as you want by adding additional $ signs in front of a variable.
6.1.1.2 Managing Variables
Three language constructs are used to manage variables. They enable you to check if certain
variables exist, remove variables, and check variables’ truth values.
isset() isset() The Determines whether a certain variable has already been declared by PHP. It
returns a boolean value true if the variable has already been set, and false otherwise, or if the
variable is set to the value NULL. Consider the following script:
if (isset($first_name)) {
print ‘$first_name is set’;
}
This code snippet checks whether the variable $first_name is defined. If $first_name is defined,
isset() returns true, which will display ‘$first_name is set.’ If it isn’t, no output is generated.
isset() can also be used on array elements (discussed in a later section) and object properties.
Here are examples for the relevant syntax, which you can refer to later:
Checking an array element:
if (isset($arr[”offset”])) {
...
}
Checking an object property:
if (isset($obj->property)) {
...
}
Note that in both examples, we didn’t check if $arr or $obj are set (before we checked the offset
or property, respectively). The isset() construct returns false automatically if they are not set.
LOVELY PROFESSIONAL UNIVERSITY 73