What PHP is....
So far you ’ ve looked at what PHP is, and what you can use it for. You ’ ve also written and tested asimple PHP script to give you a feel for how the language works. Now, in these next few chapters,
you ’ ll build a solid foundation of knowledge that you can use to create more complex applications
and Web sites in PHP.
This chapter gets the ball rolling. In it you explore some of the fundamental concepts of PHP — its
building blocks, if you will. You learn about:
Variables , which let you store and manipulate data in your scripts
Data types , including which types are available in PHP, and how to test for and
change type
PHP ’ s available operators , which you can use to manipulate information
Constants , which are useful for storing data that doesn ’ t change in your script
These are all important concepts, both in PHP and in other programming languages. Once you ’ ve
read and digested this chapter, you ’ ll be ready to move on and tackle the other features of the PHP
language.
Using Variables in PHP
Variables are a fundamental part of any programming language. A variable is simply a containerthat holds a certain value. Variables get their name because that certain value can change
throughout the execution of the script. It ’ s this ability to contain changing values that make
variables so useful.
For example, consider the following simple PHP script:
echo 2 + 2;
As you might imagine, this code outputs the number 4 when it ’ s run. This is all well and good; however,
if you wanted to print the value of, say, 5 + 6 instead, you ’ d have to write another PHP script, as follows:
echo 5 + 6;
This is where variables come into play. By using variables instead of numbers in your script, you make
the script much more useful and flexible:
echo $x + $y;
You now have a general - purpose script. You can set the variables $x and $y to any two values you want,
either at some other place in your code, or as a result of input from the user. Then, when you run the
preceding line of code, the script outputs the sum of those two values. Re - run the script with different
values for $x and $y , and you get a different result.
Naming Variables
A variable consists of two parts: the variable ’ s name and the variable ’ s value. Because you ’ ll be using
variables in your code frequently, it ’ s best to give your variables names you can understand and
remember. Like other programming languages, PHP has certain rules you must follow when naming
your variables:
Variable names begin with a dollar sign ( $ )
The first character after the dollar sign must be a letter or an underscore
The remaining characters in the name may be letters, numbers, or underscores without a
fixed limit
Variable names are case - sensitive ( $Variable and $variable are two distinct variables), so it ’ s worth
sticking to one variable naming method — for example, always using lowercase — to avoid mistakes.
It ’ s also worth pointing out that variable names longer than 30 characters are somewhat impractical.
Here are some examples of PHP variable names:
$my_first_variable
$anotherVariable
$x
$_123
Creating Variables
Creating a variable in PHP is known as declaring it. Declaring a variable is as simple as using its name inyour script:
$my_first_variable;
When PHP first sees a variable ’ s name in a script, it automatically creates the variable at that point.
Many programming languages prevent you from using a variable without first explicitly declaring
(creating) it. But PHP lets you use variables at any point just by naming them. This is not always the
blessing you might think; if you happen to use a nonexistent variable name by mistake, no error message
is generated, and you may end up with a hard - to - find bug. In most cases, though, it works just fine and
is a helpful feature.
When you declare a variable in PHP, it ’ s good practice to assign a value to it at the same time. This is
known as initializing a variable. By doing this, anyone reading your code knows exactly what value the
variable holds at the time it ’ s created. (If you don ’ t initialize a variable in PHP, it ’ s given the default
value of null .)
Here ’ s an example of declaring and initializing a variable:
$my_first_variable = 3;
This creates the variable called $my_first_variable , and uses the = operator to assign it a value of 3.
(You look at = and other operators later in this chapter.)
Looking back at the addition example earlier, the following script creates two variables, initializes them
with the values 5 and 6 , then outputs their sum ( 11 ):
$x = 5;
$y = 6;
echo $x + $y;
Understanding Data Types
All data stored in PHP variables fall into one of eight basic categories, known as data types . A variable ’ s
data type determines what operations can be carried out on the variable ’ s data, as well as the amount of
memory needed to hold the data.
PHP supports four scalar data types. Scalar data means data that contains only a single value.
About Loose Typing
PHP is known as a loosely - typed language. This means that it ’ s not particularly fussy about the type of
data stored in a variable. It converts a variable ’ s data type automatically, depending on the context in
which the variable is used. For example, you can initialize a variable with an integer value; add a float
value to it, thereby turning it into a float; then join it onto a string value to produce a longer string.
In contrast, many other languages, such as Java, are strongly - typed ; once you set the type of a variable in
Java, it must always contain data of that type.
PHP ’ s loose typing is both good and bad. On the plus side, it makes variables very flexible; the same
variable can easily be used in different situations. It also means that you don ’ t need to worry about
specifying the type of a variable when you declare it. However, PHP won ’ t tell you if you accidentally
pass around data of the wrong type. For example, PHP will happily let you pass a floating - point value to
a piece of code that expects to be working on an integer value. You probably won ’ t see an error
message, but you may discover that the output of your script isn ’ t quite what you expected! These types
of errors can be hard to track down. (Fortunately, there is a way to test the type of a variable, as you see
in a moment.)
Testing the Type of a Variable
You can determine the type of a variable at any time by using PHP ’ s gettype() function. To use
gettype() , pass in the variable whose type you want to test. The function then returns the variable ’ s
type as a string.
example, gettype( $x ) . If you need to pass more than one variable, separate them by commas. (You
learn more about how functions work, and how to use them, in Chapter 7 .)
The following example shows gettype() in action. A variable is declared, and its type is tested with
gettype() . Then, four different types of data are assigned to the variable, and the variable ’ s type is
retested with gettype() each time:
$test_var; // Declares the $test_var variable without initializing it
echo gettype( $test_var ) . “ < br / > ”; // Displays “NULL”
$test_var = 15;
echo gettype( $test_var ) . “ < br / > ”; // Displays “integer”
$test_var = 8.23;
echo gettype( $test_var ) . “ < br / > ”; // Displays “double”
$test_var = “Hello, world!”;
echo gettype( $test_var ) . “ < br / > ”; // Displays “string”
The $test_var variable initially has a type of null , because it has been created but not initialized
(assigned a value). After setting $test_var ’ s value to 15 , its type changes to integer . Setting
$test_var to 8.23 changes its type to double (which in PHP means the same as float , because all
PHP floating - point numbers are double - precision). Finally, setting $test_var to “ Hello, world! ”
alters its type to string .
In PHP, a floating - point value is simply a value with a decimal point. So if 15.0 was used instead of 15 in
the preceding example, $test_var would become a double, rather than an integer.
Changing a Variable ’ s Data Type
Earlier, you learned how to change a variable ’ s type by assigning different values to the variable.
However, you can use PHP ’ s settype() function to change the type of a variable while preserving the
variable ’ s value as much as possible. To use settype() , pass in the name of the variable you want to
alter, followed by the type to change the variable to (in quotation marks).
Here ’ s some example code that converts a variable to various different types using settype()
:
$test_var = 8.23;
echo $test_var . “ < br / > ”; // Displays “8.23”
settype( $test_var, “string” );
echo $test_var . “ < br / > ”; // Displays “8.23”
settype( $test_var, “integer” );
echo $test_var . “ < br / > ”; // Displays “8”
settype( $test_var, “float” );
echo $test_var . “ < br / > ”; // Displays “8”
settype( $test_var, “boolean” );
echo $test_var . “ < br / > ”; // Displays “1”
To start with, the $test_var variable contains 8.23 , a floating - point value. Next, $test_var is converted
to a string, which means that the number 8.23 is now stored using the characters 8 , . (period), 2 , and 3 .
After converting $test_var to an integer type, it contains the value 8 ; in other words, the fractional part
of the number has been lost permanently. You can see this in the next two lines, which convert $test_var
back to a float and display its contents. Even though $test_var is a floating - point variable again, it now
contains the whole number 8 . Finally, after converting $test_var to a Boolean, it contains the value true
(which PHP displays as 1 ). This is because PHP converts a non - zero number to the Boolean value true .
Changing Type by Casting
You can also cause a variable ’ s value to be treated as a specific type using a technique known as type
casting . This involves placing the name of the desired data type in parentheses before the variable ’ s
name. Note that the variable itself remains unaffected; this is in contrast to settype() , which changes
the variable ’ s type.
In the following example, a variable ’ s value is cast to various different types at the time that the
value is displayed:
$test_var = 8.23;
echo $test_var . “ < br / > ”; // Displays “8.23”
echo (string) $test_var . “ < br / > ”; // Displays “8.23”
echo (int) $test_var . “ < br / > ”; // Displays “8”
echo (float) $test_var . “ < br / > ”; // Displays “8.23”
echo (boolean) $test_var . “ < br / > ”; // Displays “1”
Note that $test_var ’ s type isn ’ t changed at any point; it remains a floating - point variable, containing
the value 8.23 , at all times. All that changes is the type of the data that ’ s passed to the echo statement.
casting? Most of the time, PHP ’ s loose typing handles type conversion for you automatically, depending
on the context in which you use variables and values. However, forcing a variable to be of a certain type
is useful for security reasons; if you ’ re expecting to pass a user - entered integer value to a database, it ’ s a
good idea to cast the value to an integer, just to make sure the user really did enter an integer. Likewise,
if you ’ re passing data to another program, and that program expects the data to be in string format, you
can cast the value to a string before you pass it.
Essentially, use explicit casting or settype() whenever you want to be absolutely sure that a variable
contains data of a certain type.
Operators and Expressions
So far you ’ ve learned what variables are, and how to set a variable to a particular value, as well as how
to retrieve a variable ’ s value and type. However, life would be pretty dull if this was all you could do
with variables. This is where operators come into play. Using an operator, you can manipulate the
contents of one or more variables to produce a new value. For example, this code uses the addition
operator ( + ) to add the values of $x and $y together to produce a new value:
echo $x + $y;
So an operator is a symbol that manipulates one or more values, usually producing a new value in the
process. Meanwhile, an expression in PHP is anything that evaluates to a value; this can be any
combination of values, variables, operators, and functions. In the preceding example, $x + $y is an
expression. Here are some more examples of expressions:
$x + $y + $z
$x -$y
$x
5
true
gettype( $test_var )
The values and variables that are used with an operator are known as operands .
Post a Comment