1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional Information Technology-Programming Book part 62 ppt

8 118 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 8
Dung lượng 25,38 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

For instance, you could have a variable called number that holds the value 5 or a variable called name that holds the value Chris.. The following PHP code declares variables with those n

Trang 1

Understanding Variables

Variablescontainers in which values can be stored and later retrievedare a

fundamental building block of any programming language

For instance, you could have a variable called number that holds the value 5 or a variable called name that holds the value Chris The following PHP code

declares variables with those names and values:

$number = 5;

$name = "Chris";

In PHP, a variable name is always prefixed with a dollar sign If you remember that, declaring a new variable is very easy: You just use an equals symbol with the variable name on the left and the value you want it to take on the right

Declaring Variables Unlike in some programming languages, in

PHP variables do not need to be declared before they can be used

You can assign a value to a new variable name any time you want

to start using it

Variables can be used in place of fixed values throughout the PHP language The following example uses echo to display the value stored in a variable in the same way that you would display a piece of fixed text:

$name = "Chris";

echo "Hello, ";

echo $name;

The output produced is

Hello, Chris

Naming Variables

The more descriptive your variable names are, the more easily you will remember what they are used for when you come back to a script several months after you

Trang 2

write it

It is not usually a good idea to call your variables $a, $b, and so on You probably won't remember what each letter stood for, if anything, for long Good variable names tell exactly what kind of value you can expect to find stored in them (for example, $price or $name)

Case-Sensitivity Variable names in PHP are case-sensitive For

example, $name is a different variable than $Name, and the two

could store different values in the same script

Variable names can contain only letters, numbers, and the underscore character, and each must begin with a letter or underscore Table 2.1 shows some examples

of valid and invalid variable names

Table 2.1 Examples of Valid and Invalid Variable Names

Valid Variable Names Invalid Variable Names

Using Underscores Using the underscore character is a handy way

to give a variable a name that is made up of two or more words

For example $first_name and $date_of_birth are more

readable for having underscores in place

Another popular convention for combining words is to capitalize

the first letter of each wordfor example, $FirstName and

$DateOfBirth If you prefer this style, feel free to use it in

your scripts but remember that the capitalization does matter

Expressions

When a variable assignment takes place, the value given does not have to be a

Trang 3

fixed value It could be an expressiontwo or more values combined using an

operator to produce a result It should be fairly obvious how the following example works, but the following text breaks it down into its components:

$sum = 16 + 30;

echo $sum;

The variable $sum takes the value of the expression to the right of the equals sign The values 16 and 30 are combined using the addition operatorthe plus symbol (+)and the result of adding the two values together is returned As expected, this piece of code displays the value 46

To show that variables can be used in place of fixed values, you can perform the same addition operation on two variables:

$a = 16;

$b = 30;

$sum = $a + $b;

echo $sum;

The values of $a and $b are added together, and once again, the output produced

is 46

Variables in Strings

You have already seen that text strings need to be enclosed in quotation marks and learned that there is a difference between single and double quotes

The difference is that a dollar sign in a double-quoted string indicates that the current value of that variable should become part of the string In a single-quoted string, on the other hand, the dollar sign is treated as a literal character, and no reference is made to any variables

The following examples should help explain this In the following example, the value of variable $name is included in the string:

$name = "Chris";

echo "Hello, $name";

Trang 4

This code displays Hello, Chris

In the following example, this time the dollar sign is treated as a literal, and no variable substitution takes place:

$name = 'Chris';

echo 'Hello, $name';

This code displays Hello, $name

Sometimes you need to indicate to PHP exactly where a variable starts and ends You do this by using curly brackets, or braces ({}) If you wanted to display a weight value with a suffix to indicate pounds or ounces, the statement might look like this:

echo "The total weight is {$weight}lb";

If you did not use the braces around $weight, PHP would try to find the value of

$weightlb, which probably does not exist in your script

You could do the same thing by using the concatenation operator, the period

symbol, which can be used to join two or more strings together, as shown in the following example:

echo 'The total weight is ' $weight 'lb';

The three valuestwo fixed strings and the variable $weightare simply stuck together in the order in which they appear in the statement Notice that a space is included at the end of the first string because you want the value of $weight to

be joined to the word is

If $weight has a value of 99, this statement will produce the following output: The total weight is 99lb

Trang 6

Data Types

Every variable that holds a value also has a data type that defines what kind of value it is holding The basic data types in PHP are shown in Table 2.2

Table 2.2 PHP Data Types

Data Type Description

Boolean A truth value; can be either TRUE or FALSE

Integer A number value; can be a positive or negative whole number Double (or

float)

A floating-point number value; can be any decimal number

String An alphanumeric value; can contain any number of ASCII

characters

When you assign a value to a variable, the data type of the variable is also set PHP determines the data type automatically, based on the value you assign If you want

to check what data type PHP thinks a value is, you can use the gettype function

Running the following code shows that the data type of a decimal number is

double:

$value = 7.2;

echo gettype($value);

The complementary function to gettype is settype, which allows you to override the data type of a variable If the stored value is not suitable to be stored

in the new type, it will be modified to the closest value possible

The following code attempts to convert a string value into an integer:

$value = "22nd January 2005";

settype($value, "integer");

echo $value;

Trang 7

In this case, the string begins with numbers, but the whole string is not an integer The conversion converts everything up to the first nonnumeric character and

discards the rest, so the output produced is just the number 22

Analyzing Data Types In practice, you will not use settype and

gettype very often because you will rarely need to alter the data

type of a variable This book covers this topic early on so that you

are aware that PHP does assign a data type to every variable

Type Juggling

Sometimes PHP will perform an implicit data type conversion if values are

expected to be of a particular type This is known as type juggling

For example, the addition operator expects to sit between two numbers String type values are converted to double or integer before the operation is performed, so the following addition produces an integer result:

echo 100 + "10 inches";

This expression adds 100 and 10, and it displays the result 110

A similar thing happens when a string operator is used on numeric data If you perform a string operation on a numeric type, the numeric value is converted to a string first In fact, you already saw this earlier in this lesson, with the

concatenation operatorthe value of $weight that was displayed was numeric

The result of a string operation will always be a string data type, even if it looks like a number The following example produces the result 69, butas gettype shows$number contains a string value:

$number = 6 9;

echo $number;

echo gettype(6 9);

Trang 8

We will look at the powerful range of operators that are related to numeric and string data types in PHP in Lessons 5, "Working with Numbers," and 6, "Working with Strings."

Variable Variables

It is possible to use the value stored in a variable as the name of another variable If this sounds confusing, the following example might help:

$my_age = 21;

$varname = "my_age";

echo "The value of $varname is ${$varname}";

The output produced is

The value of my_age is 21

Because this string is enclosed in double quotes, a dollar sign indicates that a

variable's value should become part of the string The construct ${$varname} indicates that the value of the variable named in $varname should become part of the string and is known as a variable variable

The braces around $varname are used to indicate that it should be referenced first; they are required in double-quoted strings but are otherwise optional The following example produces the same output as the preceding example, using the concatenation operator:

echo 'The value of ' $varname ' is ' $$varname;

Ngày đăng: 07/07/2014, 03:20