34
|
Chapter 2: Language Basics
symbol table entries for
$worker
and
$other
has a reference count of 2.
*
In other
words, that memory can be reached two ways: through
$worker
or
$other
. But after
$worker[1]
is changed, PHP creates a new array for
$worker
, and the reference count
of each of the arrays is only 1.
When a variable goes out of scope (as a function parameter or local variable does at
the end of a function), the reference count of its value is decreased by one. When a
variable is assigned a value in a different area of memory, the reference count of the
old value is decreased by one. When the reference count of a value reaches 0, its
memory is freed. This is reference counting.
Reference counting is the preferred way to manage memory. Keep variables local to
functions, pass in values that the functions need to work on, and let reference count-
ing take care of freeing memory when it’s no longer needed. If you do insist on try-
ing to get a little more information or control over freeing a variable’s value, use the
isset( )
and
unset( )
functions.
To see if a variable has been set to something, even the empty string, use
isset( )
:
$s1 = isset($name); // $s1 is false
$name = "Fred";
$s2 = isset($name); // $s2 is true
Use
unset( )
to remove a variable’s value:
$name = "Fred";
unset($name); // $name is NULL
Expressions and Operators
An
expression
is a bit of PHP that can be evaluated to produce a value. The simplest
expressions are literal values and variables. A literal value evaluates to itself, while a
variable evaluates to the value stored in the variable. More complex expressions can
be formed using simple expressions and operators.
An
operator
takes some values (the operands) and does something (for instance, adds
them together). Operators are written as punctuation symbols—for instance, the
+
and
–
familiar to us from math. Some operators modify their operands, while most do not.
Table 2-3 summarizes the operators in PHP, many of which were borrowed from C
and Perl. The column labeled “P” gives the operator’s precedence; the operators are
listed in precedence order, from highest to lowest. The column labeled “A” gives the
operator’s associativity, which can be L (left-to-right), R (right-to-left), or N (non-
associative).
* It is actually 3 if you are looking at the reference count from the C API, but for the purposes of this explana-
tion and from a user-space perspective, it is easier to think of it as 2.
,ch02.15294 Page 34 Wednesday, March 13, 2002 11:42 AM
This is the Title of the Book, eMatter Edition
Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.
Do'stlaringiz bilan baham: |