PHP2: Variables, Scope, Forms
- -
Variables and
Built-in Functions
To
write even simple PHP programs it is necessary to understand what variables
are and how to put
data in them, how to manipulate data using built-in functions , and how to control the flow of execution.
- Values are
assigned to variables
We have already seen examples of code like
this:
<?php
echo "Hello user!";
?>
In this fragment the echo function is acting on the string " Hello user! ". This string is known as a
value.
Here the value is itself
directly part of the PHP code itself - in such cases we say the value
is ' hard
coded '.
Computer
programs would be dull if all values were hard coded. We'd
never be able to call users by their names, or do much of anything
else interesting. Fortunately we can also use 'variables' to hold
values.
For
example, the statement
$userName = "Fred";
puts the value represented by the
literal string "Fred" into the
variable $userName .
Variables are
containers for data. A named variable essentially represents a place
in RAM memory where data can be stored. Therefore the assignment
statement above stores the value " Fred " in the memory location represented by the
name " userName ".
Once data is
stored in a variable it can be recalled, manipulated, echoed to the
browser, etc. For example, the results of
1:<?php
2:
3:$magicNumber =
10;
4:$magicNumber = $magicNumber + 1;
5:$userName =
"Fred";
6:
7:echo "Hello $userName, the magic number is now
$magicNumber.";
8:
9:?>
should
be fairly obvious.
This program would send to the browser "Hello Fred, the magic number is now
11."
- How is a
variable named?
A properly named variable in PHP must conform to
the rules... It is preceded by a dollar sign ($). Following the dollar
sign, the variable name must begin with either a letter (A-Z, a-z) or
an underscore (_). The rest of the name can consist of any combination
of letters, numbers and underscore characters - but not blank spaces.
Variable names are case sensitive.
Here are valid variable
names:
$pony
$Pony
$smallHorse
$small_horse
$_pony
Also, $Fred is a
different variable than $fred .
- Good variable
names
Good variable names describe the intended contents of a
variable, e.g.
$itemSubtotal= 100;
$shippingCharge =
11;
$salesTax= 5;
These names are good because they will be
easy to read and understand. Also they follow a consistent style -
each name is composed of 2 or more simple words. The first simple
word is lowercase and the others have the first letter uppercase to
mark the word breaks. This is referred to as camel-cap style.
- What can be
stored in a variable?
A variable in PHP can be assigned any kind of
PHP value. So the question is, what are the possible kinds of value in
PHP? So far in the examples we've seen 2 kinds of value: strings and numbers .
Roughly speaking these are referred to as " types " of variables.
Technically there is more than one kind of
number (e.g. fixed versus floating point), as well as special true and
false
values known as
" boolean
" - but in practice we don't
usually spend much time worrying about types in PHP. The types of
PHP variables are usually handled automatically for us anyways. For that reason, PHP is referred to as a "loosely typed" language (but typos aren't allowed).
- To
summarize...
- Any value at
all (simple or complex) can be stored in a PHP
variable.
- There are kinds of PHP values: scalars, arrays and
objects.
- Formally
speaking there are 8 PHP data types
.
- Processing HTML
forms
Forms are the way that user information reaches your scripts. To
access form data you need to reference the PHP super-global arrays:
$_GET
, $_POST and/or $_REQUEST .
- Once upon a
time...
Once upon a time PHP was different. When forms were
submitted the value in them automagically became global variables
that your scripts had access to. This was golden age, in which
anything was possible...
All
this changed with PHP 4.2...
- register_globals off since PHP
4.2
Actually, the momentous change is really just one line in
php.ini... In the old days, a variable in the config file called
register_globals was turned on, whereas now it is off by
default.
Your
script can easily access any part of the environment or HTTP
request that it
needs to - the change is that by default these data streams are not
merged willy-nilly into your global space. It's a good
thing.
The only
problem is that now programmers have to understand how to access
array elements before being able to process a simple form.
- Just enough
about arrays to be dangerous....
Arrays are lists of values - any kind of values! Each entity in an
array is called an element . The
values stored in elements can be accessed by keys .
For example, consider this code:
$favoriteFoods['tom'] =
"pancakes";
$favoriteFoods['dick'] = "broccoli";
$favoriteFoods['harry']
= "tofu burgers";
' tom ',
' dick
' and ' harry ' are the keys of the
array:
echo "Harry's favorite food is " . $favoriteFoods['harry'] ;
By the way, this array could also have been constructed
using the array construct, as follows:
$favoriteFoods= array(
'tom' => 'pancakes',
'dick' => 'broccoli',
'harry' => 'tofu
burgers' );
- $_GET, $_POST
and $_REQUEST
PHP automatically populates several magical
super-arrays with the information submitted via HTML
forms.
The most basic ones are $_GET and $_POST .
These are
automatically filled with submitted values. If the HTML form used
method GET then its values will be found in the $_GET array. If the form used method POST then
consult the $_POST array.
1:<html>
2:<head>
3:<title>Color chooser</title>
4:</head>
5:<body
bgcolor='<? echo $_POST['favoriteColor']
?>'>
6:
7:<form method=POST>
8: Color?
9: <select
name='favoriteColor'>
10: <option>Red</option>.
11: <option>Blue</option>
12: <option>Green</option>
13: <option>Yellow</option>.
14: </select>
15: <br><br>
16: <input
type=submit value="Pick">
17:</form>
18:
19:</body>
20:
21:</html>
- Working with
strings and numbers
An important aspect of working with strings and
numbers is understanding the basic operators associated with
them.
A computer
language provides built-in functions for working with its data types. At an even more fundamental
level it provides operators . An operator is a symbol that acts on values,
and "does something." Operators are built into the fabric a of a programming language -
they represent basic actions that can be performed on values and
variables.
- PHP
Operators
For example, the concatenation operator (.) compounds two "operands" that
it assumes are strings into one, as in:
echo ($firstName . " " .
$lastName); [Note the space character " "]
Meanwhile the addition operator (+) combines two "operands" by adding them
together and returning the result:
echo ($subTotal +
$shippingCharge);
- Type
juggling
Many type-sensitive operators, including " +" and " . ",
will go out of their way to interpret their operands numerically -
for example the statement
echo ("3" + 4);
will print "7", even though one
operand was ostensibly a string.
Meanwhile, the concatenation operator ('.') will likewise try to
interpret its operands as stings. For example,
echo ("3" .
4);
will
print "34", even though one operand was ostensibly an integer.
- Running a
total...
Several special operators support the common and useful
idiom of allowing a variable to accumulate value, for example the
addition
assignment operator ('+='):
...
$subTotal += $itemCost;
...
This
would be sensible inside of a " loop " through the items in a shopping
cart.
Here's a quick
conceptual example using the concatenation assignment operator ('.=')...
foreach ($randomWords
as $randomWord) {
// add a " " before the next word, except
the first time...
if ($wildNewSentence)
$wildNewSentence .= "
";
$wildNewSentence .= $randomWord;
}
- Built-in PHP
functions
The idea of a "function" is important in software.
Conceptually functions are a way for something to be implemented
once and then accessed as often as needed. Functions often receive
parameters - that is values are passed into a function when it is
called. Functions also typically return a value which the calling
code can evaluate or assign. PHP programmers define functions as
needed in our scripts and programs. At the deeper level the language
itself provides hundreds of core commands that present themselves as
" built-in "
functions.
PHP
has a very large number of built-in functions.
You'll
probably want to make frequent use of the PHP Manual @
http://www.php.net/manual/en
- Reversing
course
For fun, here's a quick page that uses the built-in
strrev() function:
1:
<?php
2:
3: $userWord = $_GET['userWord'];
4:
5: if ($userWord)
6:
echo "'$userWord' backwards is '". strrev($userWord) . "'<hr>";
7:
8:
?>
9:
10: <form>
11: Word? <input type=text
name='userWord' value='<? echo $userWord
?>'>
12: <br>
13: <input
type=submit>
14: </form>
Line #3 is the magic for accessing form
values. Line #5 checks to see if a value has been submitted.
Strrev() is used on line #6 - this line shows various ways of quoting,
concatenating and interpolating values. Line #11 has some PHP in
it to make the form value 'sticky' as a
convenience.
Tip: By
the way, cleaning up user input is a common requirement but for
some reason reversing strings doesn't seem to come up very
often.
- String
functions galore...
A complete list of PHP string functions
can be found here: http://www.php.net/manual/en/ref.strings.ph
- Number
functions
http://www.php.net/manual/en/ref.math.ph
http://www.php.net/manual/en/ref.datetime.ph
|