Page 86 - Beginning PHP 5.3
P. 86
Part II: Learning the Language
PHP has many more operators than the ones listed here. For a full list, consult http://www.php
.net/operators .
You can affect the order of execution of operators in an expression by using parentheses. Placing
parentheses around an operator and its operands forces that operator to take highest precedence. So, for
example, the following expression evaluates to 35:
( 3 + 4 ) * 5
,
As mentioned earlier, PHP has two logical “ and ” operators ( & & and ) and two logical “ or ” operators ( || ,
or ). You can see in the previous table that & & and || have a higher precedence than and and or . In fact,
and and or are below even the assignment operators. This means that you have to be careful when
using and and or . For example:
$x = false || true; // $x is true
$x = false or true; // $x is false
In the first line, false || true evaluates to true , so $x ends up with the value true , as you ’ d expect.
However, in the second line, $x = false is evaluated first, because = has a higher precedence than or .
By the time false or true is evaluated, $x has already been set to false .
Because of the low precedence of the and and or operators, it ’ s generally a good idea to stick with & &
and || unless you specifically need that low precedence.
Constants
You can also define value - containers called constants in PHP. The values of constants, as their name
implies, can never be changed. Constants can be defined only once in a PHP program.
Constants differ from variables in that their names do not start with the dollar sign, but other than that
they can be named in the same way variables are. However, it ’ s good practice to use all - uppercase names
for constants. In addition, because constants don ’ t start with a dollar sign, you should avoid naming
your constants using any of PHP ’ s reserved words, such as statements or function names. For example,
don ’ t create a constant called ECHO or SETTYPE . If you do name any constants this way, PHP will get
very confused!
Constants may only contain scalar values such as Boolean, integer, float, and string (not values such as
arrays and objects), can be used from anywhere in your PHP program without regard to variable scope,
and are case - sensitive.
Variable scope is explained in Chapter 7 .
To define a constant, use the define() function, and include inside the parentheses the name you ’ ve
chosen for the constant, followed by the value for the constant, as shown here:
define( “MY_CONSTANT”, “19” ); // MY_CONSTANT always has the string value “ 19 ”
echo MY_CONSTANT; // Displays “ 19 ” (note this is a string, not an integer)
48
9/21/09 8:51:26 AM
c03.indd 48
c03.indd 48 9/21/09 8:51:26 AM