Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

Variables

Variables in PHP are identifiers prefixed with a dollar sign ($). For example:

$name
$Age
$_debugging
$MAXIMUM_IMPACT

A variable may hold a value of any type. There is no compile- or runtime type checking on variables. You can replace a variable’s value with another of a different type:

$what = "Fred";
$what = 35;
$what = array('Fred', '35', 'Wilma');

There is no explicit syntax for declaring variables in PHP. The first time the value of a variable is set, the variable is created. In other words, setting a variable functions as a declaration. For example, this is a valid complete PHP program:

$day = 60 * 60 * 24;
echo "There are $day seconds in a day.\n";
There are 86400 seconds in a day.

A variable whose value has not been set behaves like the NULL value:

if ($uninitialized_variable === NULL) {
  echo "Yes!";
}
Yes!

Variable Variables

You can reference the value of a variable whose name is stored in another variable. For example:

$foo = 'bar';
$$foo = 'baz';

After the second statement executes, the variable $bar has the value "baz".

Variable References

In PHP, references are how you create variable aliases. To make $black an alias for the variable $white, use:

$black =& $white;

The old value of $black is lost. Instead, $black is now another name for the value that is stored in $white:

$big_long_variable_name = "PHP";
$short =& $big_long_variable_name;
$big_long_variable_name .= " rocks!";
print "\$short is $short\n";
print "Long is $big_long_variable_name\n";
$short is PHP rocks! ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata