1. The document discusses operators and flow control in PHP including math operators, assignment operators, comparison operators, logical operators, and control structures like if/else statements, switch statements, loops, and functions.
2. Regular expressions and pattern matching are introduced as ways to validate user input data with functions like ereg(), split(), and ereg_replace(). Common patterns and character classes are explained.
3. Form validation is discussed including checking for empty fields, using custom arrays for form data, and redirecting with HTTP headers. Server variables are also described.
1 of 222
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
More Related Content
php programming.pptx
1. 1
Chapter 2 - Gaining Control with
Operators and Flow Control
By Dr M.Rani Reddy
2. 2
PHP Operators and Flow Control
• Math Operators
+ Adds numbers
- Subtracts numbers
* Multiplies numbers
/ Divides numbers
% returns integer remainder from
integer division
<?php
echo "5+2 = ", 5+2, "<br />";
?>
• Math Functions
abs Absolute Value
You call functions the same as you do in most
languages. Use the name of the function and
provide the appropriate arguments.
$y = abs(-9);
echo "$y";
3. 3
List of Math Functions
• Here's some of the commonly used functions.
More are listed in the text, p. 35.
ceil rounds fractions up
exp calculates the exponent of e
floor rounds fractions down
fmod returns the floating point
remainder of the division of the
arguments
is_nan determines whether a value is
not a number
max finds the highest value
min finds the lowest value
sqrt square root
4. 4
Assignment Operator
• As in most languages the assignment
operator is =.
This means the expression on the right of the
operator is evaluated and the resulting value
is stored in the variable on the left.
$a = 4 + 3 + $b.
• There are also combined assignment
operators.
+= -+ *= /=
.= %= |= ^=
<<= >>=
$a += $b;
We'll see more of these in use later.
5. 5
Incrementing & Decrementing
• PHP includes the ++ and the -- operators that
can be used pre and post for some operation.
++$value increments $value by one, then
returns $value
--$value decrements $value by one, then
returns $value
$value++ returns $value, then increments
$value-- returns $value, then decrements
<?php
$a = $b = $c = $d = 1;
echo "$a++ gives ", $a++, "<br />";
echo "++$b gives ", ++$b, "<br />";
?>
ouputs what ?
6. 6
Operator Precedence
• new
• [
• ! ~ ++ -- (int) (float)
(string) (array) (object)
• @
• * / %
• + - .
• << >>
• < <= > >=
• == != === !==
• &
• ^
• |
• &&
• ||
• ? :
• = += -+ and so on
there are more. use parentheses to avoid
problems.
7. 7
Execution Operator
• The execution operator lets you run operating
system commands and programs, enclose
the command in backquotes (`).
<?php
$output = `date`;
echo $output;
?>
In a Unix system using bash --
Fri Aug 25 12:30:42 EDT 2006
• you can pass an argument to the system
command
<?php
$output = `ls -l *.php`;
echo $output;
?>
8. 8
String Operators
• PHP has two string operators.
concatenation .
concatenating assignment .=
• <?php
$a = "ITEC";
$b = 325;
$c = $a . " " . $b; #note coercion
# now $c = "ITEC 325"
$a .= " " . $b;
// now $a = "ITEC 325"
?>
• we'll see many more string function in PHP in
the next chapter
9. 9
Bitwise Operators
• PHP has a set of operators that can work with the
individual bits in an integer.
Note - Besides integers, you can also work with
strings using these operators; in that case, the
ASCII value of each character is used.
& AND $a & $b bits set in both $a and $b are
set
| OR $a | $b bits set in either $a or $b are
set
^ Xor $a ^ $b bits set in either $a or $b but
not both are set
- Not - $a bits set in $a are not set and
vice versa
<< shift
left
$a << $b shift left the bits in $a by the
amount in $b -- if $b is one,
multiply by two
>> shift
right
$a >> $b shift right the bits in $a by the
amount in $b -- if $b is one,
divide by two
10. 10
if Statements
• Just the standard
if (boolean expression)
php statement;
if the boolean expression evaluates to true
the statement beneath is executed, otherwise
it is not executed
can execute more than one statement by
createing a block of statements using { }
if (boolean expression)
{
phpstatement 1;
php statement 2;
php statement 3;
}
$a = 50;
if ($a > 45)
echo "$a's value is: $a";
11. 11
Comparison Operators
== equal $a == $b TRUE, if $a equals $b
=== Identical $a === $b TRUE, if $a is identical
to $b (no coercions)
!= not equal $a != $b TRUE, if $a is not equal
to $b
<> not equal $a <> $b TRUE, if $a is not equal
to $b
!== not
identical
$a !== $b TRUE, if $a is not
identical to $b (no
coercions)
< less than $a < $b TRUE, if $a is less than
$b
> greater
than
$a > $b TRUE, if $a is greater
than $b
<= less than
or equal
$a <= $b TRUE, if $a is less than
or equal to $b
>= greater
than or
equal
$a >= $b TRUE, if $a is greater
than or equal to $b
12. 12
Logical Operators
and And $a and $b TRUE, if both $a and $b
are true
or Or $a or $b TRUE, if $a or $b are true
xor Xor $a xor $b TRUE, if either $a or $b
is true, but not both
! Not !$a TRUE, if $a is false
&& And $a && $b TRUE, if both $a and $b
are true (higher
precedence than and)
|| Or $a || $b TRUE, if either $a or $b
is true (higher
precedence than or)
13. 13
else and elseif
• $a = 20;
$b = 40;
$c = "40chairs";
if ($a >= $b)
{ echo "$a is larger, value is : $a"; }
else
{ echo "$b is larger, value is : $b";}
if ($a == $c)
{ echo "a & c are the same."; }
else
{ echo "a & c are not the same."; }
if ($a === $c)
{ echo "a & c are the same."; }
elseif ($a == $c)
{ echo "a & c are different types."; }
else
{echo "a & c have different values."}
• comparisons of strings and characters are
based on the ASCII character codes
14. 14
switch Statements
• switch statements are used for testing
multiple conditions. The same tests can be
built with multiple if statements, however,
switch statements help to organize code.
(use ints, floats, or strings)
$temp = 70;
switch ($temp)
{
case 70:
echo "Nice weather.";
break;
case 80:
{
echo "Warm today. <br />";
echo "Old bones like warm weather.";
break;
}
case 90:
echo "Hot!!!";
break;
default:
echo "temperature not in range";
}
15. 15
for Loops
• for (expression1;expression2;expression3)
statement;
for ($ctr = 1; $ctr < 10; $ctr++)
{
print ("$ctr = : $ctr <br />");
}
• expressions in a for loop can handle multiple
indexes, as long as you separate them with
the comma operator.
for ($var1=2, $var2=2; $var1<5; $var1++)
{
echo "var1 is : $var1 ", " double it : $var1
* $var2 ":
}
• probably easier to use nested for loops
16. 16
while Loops
• standard loop that keeps executing until the
initial condition is false
$ind = 10;
while ($ind > 1)
{
echo "ind = $ind";
$ind--;
}
• often used when reading files
open_file();
while (not_at_end_of_file())
{
$data = read_one_line_from_file();
echo $data;
}
17. 17
do … while Loops
• just like a while loop except the condition is
checked at the end of the loop instead of the
beginning, so it's always executed at least
once
do
{
echo $val, "<br />";
$val *= 2;
}
while ($val < 10);
18. 18
foreach Loops & break
• the foreach loop makes working with arrays
much easier.
<?php
$arr = array("apples","oranges","grapes");
foreach ($arr as $value)
{
echo "Current fruit: $value <br />";
}
• in case you want to stop a loop or swich
statement early, the break statement ends
execution of the current for, foreach, while,
do…while, or switch statement.
while (not_at_end_of_file())
{
$data = read_one_line_from_file();
echo $data;
if ($data == "quit")
break;
}
19. 19
continue Statement
• the continue statement can be used inside a
loop to skip the rest of the current loop
iteration and continue with the next iteration.
for ($val = -2; $val < 2; $val++)
{
if ($val == 0)
{ continue; }
echo 1/$val, " <br />";
}
skipped the division by 0
• php has alternate syntax for if, while, for,
foreach, and switch statements
for ($ctr=0; $ctr < 5; $ctr++):
echo "Print this five times.";
endfor;
20. 20
Chapter 6 – Creating Web Forms and
Validating User Input
By Dr M.Rani Reddy
21. 21
Developing Web Applications
• In developing web application, building the
forms is just the first step in collecting data.
Validating input data must be done to avoid
wasted processing and to reduce effective
response time.
A typical code structure that validates data
might be:
validate_data();
if (count($errors) != 0)
{
display_errors();
display_welcome();
}
else
{
process_data();
}
22. 22
Displaying All Form Data
• Here's a program that will display all the data
being sent to the server program, a very
useful debugging tool
<?php
foreach($_REQUEST as $key => $val)
{
if(is_array($val))
{
foreach($val as $item)
{
echo $key, " => ", $val, "<br />";
}
}
else
{
echo $key, " => ", $val, "<br />";
}
}
?>
23. 23
Server Variables
• There's a special superglobal array,
$_SERVER, that contains a great deal of
information about what's going on with your
web application. For example,
$_SERVER['REQUEST_METHOD'] holds the
request method that was used ("GET",
"POST", and so on)
'AUTH_TYPE'
holds the authentication type
'DOCUMENT_ROOT'
root directory under which the script
is executing, defined in server config
'GATEWAY_INTERFACE'
revision of the CGI spec. that the server
is using, i.e., CGI/1.1
'PHP_SELF'
filename of the currently executing
script
'REMOTE_ADDR'
ip address from which the user is
viewing the current page
24. 24
Server Variables (cont.)
• 'REQUEST_METHOD'
request method used to access the page
-- GET, POST, HEAD, PUT
'SERVER_NAME'
name of the server host under which
the script is executing
there are more see page 170 & 171 in your
text
25. 25
Useful HTTP Headers
• A number of HTTP headers are built into the
$_SERVER array as well. For example,
$_SERVER['HTTP_USER_AGENT'] holds the
type of the user's browser.
Some of the other entries --
'HTTP_REFERER'
the address of the page (if any) that
referred the user agent to the current
page.
'HTTP_USER_AGENT'
text in the user_agent: header from the
current request, if there is one. Denotes
the browser that is accessing the page.
26. 26
Redirecting with HTTP Headers
• You can read and create HTTP headers to
send back to the browser. The header()
function is used to create HTTP headers
in the following script:
the button value in the form has one of the
following values (the names of php files)
phpbuttons
phplistbox
phptextarea
To redirect via a php script
<?php
$redirect = "Location: " .
$_REQUEST['Button'] . ".html";
echo header($redirect);
?>
redirecting is often used with image maps
27. 27
Custom Arrays for Form Data
• You can use PHP to create a custom array for
form data by giving each text field control a
name with square brackets
Set the name attribute in the form field as in
the following
<input name="textdata[name]" type="text"
size="20" maxlength="30" />
in the receiving script
<?php
$text = $_REQUEST['textdata'];
echo $text['name'];
?>
28. 28
Single PHP Page Application
• Many web applications are written with a
single PHP page. Say you wanted to get a
single piece of data (like name) from a user
and then you wanted to display that name
with some other request for data
<html><head><title>Single PHP Page</title>
</head>
<body>
<h2>Using Text Fields</h2>
<?php
if (isset($_REQUEST["Name"]))
{
?>
<h2> Using Text Fields</h2>
<p>Your name is:
<?php
echo $_REQUEST["Name"]
}
else {
?>
<form method="post" action="phptext.php">
What's your name?
<input name="name" type="text" /><br
/><br/>
30. 30
Validating Data
• assume we're getting a name in a text field
If there's no entry in the text field we can
check like in the following
function validate_data()
{
global $errors;
if ($_REQUEST["Name"] == "")
{
$errors[] = "<span style="border-
style:red;
color:blue;"> .
Please enter your name.
</span>";
}
}
Note the structure for an php/html document
that includes a validating function.
((slide 2)) pp. 181-185 in your text
31. 31
Regular Expressions
• PHP can implement regular expressions for
pattern matching. This is the way most
validation of entered data is accomplished.
Here are three functions used in pattern
matching.
ereg(), split(), ereg_replace
Use ereg(), to check if a string contains a
match pattern:
$ret = ereg("search pattern", "target string");
$ret will be set to 1if the pattern is found 0
otherwise
search pattern is the regular expression
target string is the string to be searched
32. 32
Pattern Matching Example
• $name = 'Jake Jackson';
$pattern = 'ke';
if (ereg($pattern, $name))
{
print ("Match");
}
else
print ("No match");
outputs match since "ke" is found
regular expressions are defined by an
industry standard IEEE POSIX 1003.2
standard
there are several special characters that can
be used to build patterns
^ means the pattern must appear at the start
of the target string
$ means the pattern must appear at the end
of the target string
33. 33
Pattern Matching Characters
•
+ matches 1 or more occurrences
* matches 0 or more occurrences
? matches 0 or 1 occurrences
. wildcard symbol matches any single
character
| or symbol either pattern can be matched
[] any of the included set can be matched
^ at the beginning of the set means not
these characters
{} specify a number of repetitions of a
character in the pattern
-- note there are more, but these provide a
good start
34. 34
Pattern Matching Example
• suppose we want to test to see that a client
inputs a valid area code
first -- what do we know about area codes
-- 3 digits
-- first digit can't be 0
-- can't be 911
• remember we can group characters using
parentheses
35. 35
Predefined Character Classes
• there are several predefined character
classes that are typically used in pattern
matching regular expressions
[[:space:]] matches a single space
[[:alpha:]] matches any word character
(uppercase or lowercase letters)
[[:upper:]] matches any single uppercase
letter
[[:lower:]] matches any single lowercase
letter
[[:digit:]] matches any valid digit (0-9)
[[:punct:]] matches an punctuation mark
(? , . " ' ! ; : )
36. 36
Using split()
• use split() to break a string into different
pieces based on the presence of a match
pattern
$output = split(search_patt, target_st, max);
$output -- is an array variable that will contain
the matches
search_patt -- this is the pattern to be
matched
target_st -- the string to be searched
max -- maximum number of matches to make
(this parameter is optional)
$line = 'Baseball, hot dogs, apple pie';
$item = split ( ',' ,$line);
$item[0] will contain Baseball
$item[1] will contain hot dogs
$item[2] will contain apple pie
37. 37
eregreplace()
• works like ereg, but a second string is
specified to replace the part of the target
string that matches the pattern
$start = 'AC1001:Hammer:15:150';
$end = eregreplace('Hammer', 'Drill', $start);
$end will now contain
'AC1001:Drill:15:150'
38. 38
Removing HTML Tags from Input
• something you must watch out for --- html in a
user's text box, especially if you're going to
display that text. Malicious users can put
some nasty HTML (including JavaScripts) into
submitted text, which would be executed if
you display that text in a browser. You can
use the PHP strip_tags function to remove all
HTML tags from text.
function process_data()
{
$ok_text = strip_tags($_REQUEST["name"]);
}
• if you don't want to strip HTML tags, but you
want to render them harmless, you can use
the htmlentities function instead, which
encodes HTML tags. For example,
<b>Charles</b> would be converted to
<b>Charles</b>
a browser will display this as <b>Charles</b>
39. 39
Validating with JavaScript
• using JavaScript embedded in an input form
provides for validation of data before it's sent
to the server.
<form name="fm1" action="servpg.php"
method="post"
onsubmit="return checker()" >
once the user clicks on the submit button the
checker() javascript will be run. It can do
pattern matching and other validation on the
data in the form fields. If it returns false, the
query string will not be sent to the server
application. If it returns true, it will. If the
javascript detects a problem with the data it
can post a message to the user (typically
using a dialog box) which will prompt them to
correct the data. After the correction is made
the user can submit the data again.
40. 40
HTTP authentication
• PHP allows you to determine whether the user
has been authorized by checking the
PHP_AUTH_USER key in $_SERVER. If
$_SERVER['PHP_AUTH_USER'] has been set
, the user is welcomed by name - otherwise,
the script is terminated with the PHP exit
function.
<?php
if (!isset($_SERVER['PHP_AUTH_USER']))
{
header('WWW-Authenticate:
Basic realm="workgroup"');
header('HTTP/1.0 401 Unauthorized');
echo 'Sorry, you are not authorized.';
exit;
}
else
{
echo "Welcome,
$_SERVER['PHP_AUTH_USER'].";
}
?>
42. 42
Supported Databases
• Many including Adabas, dBase, Empress,
FilePro,Oracle , IBM DB2, Informix, and more.
• One of the most popular Databases is MySQL
is free and can be downloaded at:
http://www.mysql.com. This book's examples
are based on MySQL version 4.0.
• Later the PHP DB module will be shown. DB
provides a layer of abstraction over database
operations, leeting the client work with many
different database servers using the same
function calls. The DB module lets the user
access all the database servers using the
same function calls, however using native
built-in support is much faster
• Manuals for PHP support for the various
database servers can be found at:
http://www.php.net/dbname
43. 43
Basic SQL
• To interact with databases in PHP, SQL
(Structured Query Language) is used.
Assume a table named fruit:
SELECT * FROM fruit
// selects all records from table fruit
In PHP :
$query = "SELECT * FROM fruit";
$result = mysql_query($query) or
die ("Query Failed: ". mysql_error());
// selects specific fields
SELECT name, number FROM fruit
// use where clause
SELECT * FROM fruit WHERE name="apples"
// can also use >, >=, <, <= operators
44. 44
Basic SQL (cont)
• // use in clause
SELECT * FROM fruit WHERE name IN
("apples","oranges")
// can add logical operators
SELECT * FROM fruit WHERE name NOT IN
("apples","oranges") AND number IS NOT
NULL
//can order a recordset descending
SELECT * FROM fruit ORDER BY name DESC
// can delete records
DELETE FROM fruit WHERE name NOT
IN ("apples","oranges")
// use UPDATE to change value
UPDATE fruit SET number="2006" WHERE
name = "apples"
// insert new data
INSERT INTO fruit (name,number) VALUES
('apricots', '203')
45. 45
Database Connections in PHP
• At RU, the PHP server is set-up with a
connection to a continuously running MySQL
database server
• To connect to a database use mysql_connect
command and provide the host, username,
and password
$host = 'localhost';
$user = 'jcdavis';
$pass = 'abcdef'; // your database password
$connection =
mysql_connect($host,$user,$pass) or
die ("Couldn't connect to dbase");
// now connect to the specific database
// at RU your database name is the same
// as your username
$db = mysql_select_db($user);
// now you can execute queries with
// mysql_query
mysql_close
46. 46
Set Up Your MySQL Database at RU
• https://php.radford.edu
• go to this URL for information
https://php.radford.edu/~mysql-php/
• use the MySQL admin tool to set up a table
called fruits
(use lower case field names)
name number
apples 501
oranges 255
pears 299
47. 47
Other Data Types?
• MySQL supports many other data types beyond
TEXT and INT. Here are a few :
– TEXT specifies that the table column can
hold a large amount of character data. It can
use space inefficiently since it reserves
space for up to 65,535 characters.
– CHAR(N) specifies a table column that holds
a fixed length string of up to N characters (N
must be less than 256).
– VARCAR(N) specifies a table column that
holds a variable length string of up to N
characters and removes any unused spaces
on the end of the entry.
48. 48
Other Data Types?
– INT specifies a table column that holds an
integer with a value from about –2 billion to
about 2 billion.
– INT UNSIGNED specifies a table column
that holds an integer with a value from 0 to
about 4 billion.
– SMALLINT specifies a table column that
holds an integer with a value from –32,768
to 32,767.
– SMALLINT UNSIGNED specifies a table
column that holds an integer with a value
from 0 to 65,535.
– DECIMAL(N,D) specifies a number that
supports N total digits, of which D digits
are to the right of the decimal point.
49. 49
Creating Database Tables
• Once database instance is created need to create
your tables.
– Use SQL CREATE TABLE command
CREATE TABLE Products
(ProductID INT,
Product_descr TEXT);
The name of
the table. First table column can
hold integer data.
SQL commands are shown in upper case but
either upper or lower case can be used.
Second table column can
hold character data.
50. 50
Some additional CREATE TABLE
Options
• Can specify some additional options in CREATE
TABLE:
CREATE TABLE Products
(ProductID INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY,
Product_desc VARCHAR(50),
Cost INT,
Weight INT,
Numb INT);
An INT UNSIGNED means
that ProductID must be
positive values.
ProductID must be
specified for each row.
Automatically add
one to each new
ProductID.
Make this
the primary
key for table.
Up to 50
characters
long
51. 51
Issuing CREATE TABLE From PHP
Script Segment
1. $connect = mysql_connect($server, $user, $pass);
2. if ( !$connect ) {
3. die ("Cannot connect to $server using $user");
4. } else {
5. mysql_select_db('MyDatabaseName');
6. $SQLcmd = 'CREATE TABLE Products(
ProductID INT UNSIGNED NOT NULL
AUTO_INCREMENT PRIMARY KEY,
Product_desc VARCHAR(50), Cost INT,
Weight INT, Numb INT )';
7. mysql_query($SQLcmd, $connect);
8. mysql_close($connect);
9. }
Issue the SQL query
to the database.
Connect to
MySQL
52. 52
Inserting Data
• Once database is created will need to insert
data
• Use the SQL INSERT command
INSERT INTO Products VALUES
( '0', 'Hammer', 5, 12, 123 );
Each item goes into a
separate table column in a table row.
Table Name
53. 53
Retrieving Data
• To retrieve all data, use following SQL command
• For example
$connect = mysql_connect('Localhost',
'phpgm','mypasswd');
$SQLcmd = 'SELECT * FROM Products';
mysql_select_db('MyDatabase');
$results_id = mysql_query($SALcmd, $connect
SELECT * FROM TableName;
The asterisk ("*")
means get all the data
The name of the table to
get the data from.
SQL SELECT
Statement.
54. 54
Using mysql_fetch_array
• The mysql_fetch_array function can be used
to get successive rows from a table in a while
loop and get each field value from each row
(record).
Assume the fruits table has two fields name
and number, like the following.
apples 1020
oranges 3329
bananas 442
pears 235
$conn = mysql_connection($host, $user,
$pass);
$db = mysql_select_db($user, $conn);
// remember at RU username = dbname
$query = "SELECT * FROM fruit";
$result = mysql_query($query);
echo "<table border=”5” >";
echo "<tr>";
echo "<th>Name</th><th>Number</th>";
echo "</tr>";
56. 56
Searching For Specific Records
• Use the SELECT SQL statement with a
WHERE clause
SELECT * FROM TableName WHERE (test_expression);
The
asterisk
(“*”)
means
look at all
table
columns.
Specify the
table name
to look at.
Specify a test expression
to evaluate
57. 57
Selected WHERE CLAUSE
Test Operators
Ops SQL Example
= SELECT * FROM Products
WHERE (product_desc='hammer');
> SELECT * FROM Products WHERE
(Cost > '5');
< SELECT * FROM Products WHERE
(Numb < '3');
>= SELECT * FROM Products WHERE
(Weight >= '10');
<= SELECT * FROM Products WHERE
(Cost <= '3');
58. 58
Update, Delete Example
• sample update query
$query = "UPDATE fruit SET number = 234
WHERE name = 'pears'";
$result = mysql_query($query) or
die ("Query Failed");
• sample delete query
$query = "DELETE * FROM fruit WHERE
name = 'apples' ";
$result = mysql_query($query) or die();
• sample insert
$query = "INSERT INTO fruit (name, number)
VALUES('grapes','200')";
59. 59
Pear DB Module
• PHP supports the DB module, which gives
you a level of abstraction that smoothes over
the details of working with different database
servers. When you use DB, you can use the
same functions to access your data; if you
switch database server types, you just have
to change the name of the database server
you're using.
DB is a PHP extension managed by PEAR, the
PHP Extension and Application Repository.
The PEAR module has to be installed when
you configure your PHP installation on the
Apache server.
60. 60
PEAR DB Example
• Example of using the DB module's functions
to read a MySQL database
// at the top of the PHP
require 'DB.php';
// connect using the DB connect method
$db = DB::connect('dbname://username:
password@server/databasename);
$query = "SELECT * FROM fruit";
$result = $db->query($query);
// you can recover a row of data using the
fetchRow method.
63. What is OOP?
Object Oriented Programming (OOP) is the idea of
putting related data & methods that operate on
that data, together into constructs called classes.
When you create a concrete copy of a class, filled
with data, the process is called instantiation.
An instantiated class is called an object.
64. Basic Class Structure
Two types of
constructs
properties:
The variables that
hold the data
methods:
The functions that
hold the logic
class Animal
{
// The following are properties:
public $weight;
public $legs = 4; // A default value
// The following is a method:
public function classify() {
/* ... */
}
public function setFoodType($type) {
/* ... */
}
}
65. Instantiation & Access
instantiate
by using the new
keyword
acces
s properties
and methods
via ->
class Animal
{
public $weight;
public $legs = 4;
public function classify() { /* ... */ }
public function setFoodType($type) { /* ... */ }
}
$horse = new Animal();
echo $horse->legs;
$horse->setFoodType("grain");
66. Constructors
A class can have a
method called a
constructor.
This method, named
construct, allows you
to pass values when
instantiating.
class Animal
{
// The following are properties:
public $weight;
public $legs = 4; // A default value
// The following is a method:
public function classify() { /* ... */ }
public function setFoodType($type) { /* ... */ }
// Constructor:
public function construct($weight) {
$this->weight = $weight;
}
}
$cat = new Animal(13.4);
67. Privacy & Visibility
Within a class, methods &
properties have three
levels of privacy
public
modified & accessed by anyone
private
only accessed from within
the class itself
protected
only be accessed from within
the class, or within a child
class Animal
{
protected $weight; // Accessible by children
public $legs = 4; // Publicly accessible
public function construct($weight) {
$this->setWeight($weight);
}
private function setWeight($weight) {
$this->weight = $weight;
}
}
$cat = new Animal(13.4);
echo $cat->weight; // Fatal Error
68. Static & Constants
Constants are
immutable properties.
Methods and
properties can be
static making them
accessible without
instantiation.
Access both via ::
class Math
{
const PI = 3.14159265359; // Constant:
public static $precision = 2; // Static property:
// Static method:
public static function circularArea($radius) {
$calc = self::PI * pow($radius, 2);
return round($calc, self::$precision);
}
}
Math::$precision = 4;
$answer = Math::circularArea(5);
69. Referencing Classes from within
$this-
> References the
object
self::
Reference static & const
<class_name>::
Same as self (within context)
static::
Late Static Binding
(more on this later)
class Math
{
const PI = 3.14159265359; // Constant
public static $precision = 2; // Static property
private $last; // Private property
public function circularArea($radius) {
$this->last = Math::PI * pow($radius, 2);
return round($this->last, self::$precision);
}
}
71. Inheritance
Through the extends keyword, this allows one class to be a copy of another
and build upon it. The new class is called the child, and the original the parent.
class Person {
public $first;
public $last;
public function construct($first, $last) {
$this->first = $first;
$this->last = $last;
}
public function name() {
return "{$this->first} {$this->last}";
}
}
class Employee extends Person {
public $title;
public function name() {
return $this->title;
}
}
class Intern extends Employee {
protected $title = 'Intern';
}
72. Accessing Your Parent
You can also
acces
s properties &
methods in the
parent by using
the keyword
parent::
class Person {
public $name;
public function construct($name) {
$this->name = $name;
}
public function announcement() {
return "{$this->name}";
}
}
class Employee extends Person {
public $job;
public function announcement() {
return parent::announcement . ", " . $this->job;
}
}
73. Stopping Extension
Classes can prevent
children overriding
a method
Uses final keyword
Attempting to
override a final
causes a fatal error
class A {
public function construct() {
$this->notify();
}
final public function notify() {
echo "A";
}
}
// Causes a fatal error:
class B extends A {
public function notify() {
echo "B";
}
}
74. Final Classes
Entire classes may
also be declared as
final to prevent
extension
completely
final class A
{
public function construct() {
$this->notify();
}
public function notify() {
echo "A";
}
}
76. Abstract Class
abstract class DataStore
{
// These methods must be defined in the child class
abstract public function save();
abstract public function load($id);
// Common properties
protected $data = [];
// Common methods
public function setValue($name, $value) {
$this->data[$name] = $value;
}
public function getValue($name) {
return $this->data[$name];
}
}
Defines an
‘incomplete’ class
using abstract
keyword on both
class & methods
Children need to
implement all
abstract methods
for the parent
77. Abstract
Contract
All abstract methods
must be implemented
or this class must be
abstract as well
Method signatures
must match exactly
class FileStore extends DataStore {
private $file;
public function load($id) {
$this->file = "/Users/eli/{$id}.json";
$input = file_get_contents($this->file);
$this->data = (array)json_decode($input);
}
public function save() {
$output = json_encode($this->data)
file_put_contents($this->file, $output);
}
}
$storage = new FileStore();
$storage->load('Ramsey White');
$storage->setValue('middleName', 'Elliott');
$storage->save();
78. Interfaces
An interface defines
method signatures that an
implementing class
must provide
Similar to abstract methods,
but sharable between classes
No code, No properties just
an interoperability framework
interface Rateable
{
public function rate(int $stars, $user);
public function getRating();
}
interface Searchable
{
public function find($query);
}
79. Interface Implementation
Uses the
implements
keyword
One class may
implement multiple
interfaces
class StatusUpdate implements Rateable, Searchable {
protected $ratings = [];
public function rate(int $stars, $user) {
$this->ratings[$user] = $stars;
}
public function getRating() {
$total = array_sum($this->ratings);
return $total/count($this->ratings);
}
public function find($query) {
/* ... database query or something ... */
}
}
80. Interface Extension
It is possible for an
interface to extend
another interface
Interfaces can
provide constants
interface Thumbs extends Rateable {
const THUMBUP = 5;
public function thumbsUp();
public function thumbsDown();
}
class Chat extends StatusUpdate implements Thumbs {
public function rate(int $stars, $user) {
$this->ratings[] = $stars;
}
public function thumbsUp() {
$this->rate(self::THUMBUP, null);
}
public function thumbsDown() {
$this->rate(0, null);
}
}
82. Traits
Enable horizontal
code reuse
Create code and
inject it into
diferent classes
Contains actual
implementation
// Define a simple, albeit silly, trait.
trait Counter
{
protected $_counter;
public function increment() {
++$this->_counter;
}
public function decrement() {
--$this->_counter;
}
public function getCount() {
return $this->_counter;
}
}
83. Using Traits
Inject into a class
with the use
keyword
A class can include
multiple traits
class MyCounter
{
use Counter;
/* ... */
}
$counter = new MyCounter();
$counter->increment();
echo $counter->getCount(); // 1
85. You mentioned
this before
Traditionally when
you use self:: in a
parent class you
always get the value
of the parent.
class Color {
public static $r = 0;
public static $g = 0;
public static $b = 0;
public static function hex() {
printf("#%02x%02x%02xn",
self::$r, self::$g, self::$b);
}
}
class Purple extends Color{
public static $r = 78;
public static $g = 0;
public static $b = 142;
}
Color::hex(); // Outputs: #000000
Purple::hex(); // Outputs: #000000 - Wait what?
86. Enter Late
Static Binding
By using the
static:: keyword it
will call the child’s
copy.
class Color {
public static $r = 0;
public static $g = 0;
public static $b = 0;
public static function hex() {
printf("#%02x%02x%02xn",
static::$r, static::$g, static::$b);
}
}
class Purple extends Color{
public static $r = 78;
public static $g = 0;
public static $b = 142;
}
Color::hex(); // Outputs: #000000
Purple::hex(); // Outputs: #4e008e - Right!
87. Affects
Methods Too
Allows a parent to
rely on a child’s
implementation of
a static method.
const work as well
class Color {
public $hue = [0,0,0];
public function construct(Array $values) {
$this->hue = $values;
}
public function css() {
echo static::format($this->hue), "n";
}
public static function format(Array $values) {
return vsprintf("#%02x%02x%02x", $values);
}
}
class ColorAlpha extends Color{
public static function format(Array $values) {
return vsprintf("rgba(%d,%d,%d,%0.2f)", $values);
}
}
$purple = new Color([78,0,142]);
$purple->css(); // Outputs: #4e008e
$purple50 = new ColorAlpha([78,0,142,0.5]);
$purple50->css(); // Outputs: rgba(78,0,142,0.50)
89. Defining Namespaces
Namespaces let
you have multiple
libraries with
identically named
classes & functions.
Define with the
namespace keyword
to include all code
that follows.
<?php
namespace WorkLibrary;
class Database {
public static connect() { /* ... */ }
}
<?php
namespace MyLibrary;
class Database {
public static connect() { /* ... */ }
}
90. Sub-namespaces
Use a backslash ‘’
to create these
<?php
namespace MyLibraryModel;
class Comments {
public construct() { /* ... */ }
}
<?php
namespace TrebFrameworkUtility;
class Cache {
public construct() { /* ... */ }
}
91. Using Namespaces
Use the fully
qualified name
Import via the use
keyword
Alias when importing
via as keyword
Reference builtin
classes with top level
$db = MyProjectDatabase::connect();
$model = new MyProjectModelComments();
use MyProjectDatabase;
$db = Database::connect();
$images = new DateTime();
use MyProjectModelComments as MyCo;
$model = new MyCo();
93. Magic?
All magic methods
start with __
Allow for code that is
not directly called to run
Often have
counterparts, so just as
__construct() we have
__destruct() which runs
on object cleanup
class UserORM {
public $user;
private $db;
function construct($id, PDO $db) {
$this->db = $db;
$sql = 'SELECT * FROM user WHERE id = ?';
$stmt = $db->prepare($sql)->execute([$id]);
$this->user = $stmt->fetchObject();
}
function destruct() {
$sql = 'UPDATE user
SET name = ?, email = ? WHERE id = ?';
$stmt = $db->prepare();
$stmt->execute($this->user->email
$this->user->name, $this->user->id);
}
}
$oscar = new User(37);
$oscar->user->email = 'oscar@example.com';
94. __get and __set
__get
Called when an reading
an unknown property.
__set
Called when writing
an unknown property
Often used for storage
classes & overloading
class Data
{
protected $_data = [];
public function set($name, $value) {
$this->_data[$name] = $value;
}
public function get($name) {
return isset($this->_data[$name])
? $this->_data[$name] : NULL;
}
}
$o = new Data();
$o->neat = 'Something';
echo $o->neat;
95. __isset and __unset
_
_isset
Called
when
isset()
is
reques
ted on
an
unkno
wn
proper
ty
_
_unset
Called
when
unset()
is
reques
ted on
an
unkno
wn
proper
ty
class DataAll extends Data
{
public function isset($name) {
return isset($this->_data[$name]);
}
public function unset($name) {
unset($this->_data[$name]);
}
}
$o = new DataAll();
$o->phone = 'iPhone';
$o->desktop = true;
if (isset($o->desktop)) {
unset($o->phone);
}
96. __call and __callStatic
These two methods
are called when you
attempt to access
an undeclared
method
class Methods
{
public function call($name, $args) {
$pretty = implode($args, ",");
echo "Called: {$name} with ({$pretty})n";
}
public static function callStatic($name, $args) {
$count = count($args);
echo "Static call: {$name} with {$count} argsn";
}
}
// Output - Static call: sing with 2 args
Methods::sing('Barbara', 'Ann');
// Output - // Called: tea with (Earl Gray,Hot)
$m = new Methods();
$m->tea('Earl Gray', 'Hot');
97. __invoke
__invoke
allows your object
to be called as a
function.
class TwoPower {
public function invoke($number) {
return $number * $number;
}
}
$o = new TwoPower();
$o(4); // Returns: 16
98. __toString
__toString
determines what
happens when you
echo your class.
c
l
a
s
s
D
o
u
b
l
e
r
{
p
r
i
v
a
t
e
$
n
;
public
function
construct($numb
er) {
$this->n =
$number;
}
public function toString() {
return "{$this->n} * 2 = " . $this->n * 2;
}
}
$four = new Doubler(4);
echo $four; // Output: 8
99. And more…
__sleep() and __wakeup()
control how your object is
serialized & unserialized.
__set_state() lets you
control exported properties
when var_export is
__debugInfo() lets you
change what a var_dump of
your object shows.
__clone() lets you modify
your object when it
becomes cloned.
100. 100
Chapter 5 – Handling HTML Controls
in Web Pages
Dr M.Rani Reddy
101. 101
HTML Form Fields
• in this chapter, we look at how to read data
from form fields on html documents
• buttons
• checkboxes
• hidden fields
• image maps
• lists
• passwords
• radio buttons
• reset button
• select (Menus)
• submit button
• text areas
• text fields
102. 102
Handling Client Data
• Review
an html document may contain a form. A
form tag includes an action attribute, that
specifies the server side script to send the
form data to
<form action="https://php.radford.edu/
~jcdavis/phpscript.php"
method = "post" >
<input type="text" name="txt1" size="20"
maxlength = "30" />
<input type="submit" value="submit data" />
</form>
if method is post, the data will be accessed
via the $_POST array, if method is get then
the data will be in $_GET array. the
$_REQUEST array holds data from both post
and get. These are superglobal arrays.
103. 103
html Form
• form tag
<form name="fm1"
action="https://php.radford.ed …"
method = "post" >
form field examples ---
<p>Enter first name:
<input type="text" size="20"
maxlength="30" name="fn" />
</p>
<p>
<input type="checkbox" name="chk1"
value="book1" checked="checked" />
<input type="radio" name="age"
value="under20" />Under 20<br />
<input type="radio" name="age"
value="21-40" />21 - 40
</p>
104. 104
form Fields (cont.)
• <input type="submit" value="Submit Data" />
<input type="reset" value="Clear Form" />
Menu's and text area's can also be used
collect data on an html form.
Processing data.
in php code
from a text box
$txt = $_POST["fn"];
from a check box, if a check box has been
checked it's value will be included in the
query string
$chk1 = $_POST["chk1"];
$chk1's value will be "book1"
105. 105
Getting data from RB's
• <input type="radio" name="age"
value="<20" />Under 20<br />
<input type="radio" name="age"
value="20-40" />20-40<br />
<input type="radio" name="age"
value="over 40" /><br />
--------------------
receiving code
<?php
$age = $_POST["age"];
• What will $age value be if the first radio
button is clicked?
106. 106
Hidden Fields
• let's you store hidden data in html documents
say you had a multi-form application, so the
user fills out one form and clicks on submit.
the server application collects the data and
then wants to have the user enter more info.
on a new form. hidden fields can be used to
insert this data into the second form, so it will
return when the submit button on the second
form is clicked.
<input type="hidden" name="hide1"
value="under 20" />
when the second form is submitted, the data
can be retrieved as you would for a text field
107. 107
Password Form Fields
• In PHP these are nearly the same as text
boxes. However, the characters the user
enters into the text field are not echoed to the
screen. Rather an asterisk is echoed so the
password can not be read by casual viewers
of the screen.
<input type="password" name="pass1" />
it is read in php just like a text field.
<?
$password = $_POST["pass1"];
Note -- the password is not necessarily
encrypted in the query string
108. 108
Image Maps
• PHP supports html image maps, which are
clickable images full of hot spots, although
you work with them differently in php.
to create an image map you use
<input type="image" name="imap"
src="imap.jpg" />
when the user clicks the map, the mouse
location is sent to the server.
$xloc = $_POST["imap_x"];
when you know where the map was clicked
you can use that info. to take different actions
109. 109
Uploading Files
• HTML forms can be used to upload files.
Assume you wish to upload a file named
message.txt and make this text available to
the php server script
<form enctype="multipart/form-data"
action="phpfile.php" method="post" />
Upload this file:
<input name="userfile"
type="file" />
<input type="submit" value="Send File" />
</form>
110. 110
Reading Uploaded Files
• There's another superglobal array $_FILES,
it gives you access to the uploaded file
$_FILES['userfile']['name']
original name of the file from user
$_FILES['userfile']['type']
MIME type of the file
for example -- "text/plain" or "image/gif")
$_FILES['userfile']['size']
size of the uploaded file in bytes
$_FILES['userfile']['tmp_name']
temporary filename of the file in
which the uploaded file was stored on
the server
when a file is uploaded, it's stored as a
temporary file on the server, and you access
using - $_FILES['userfile']['tmp_name']
111. 111
Reading Uploaded Files (cont)
• We'll see more about reading and writing files
in chapter 6, but briefly here's the method
used to open and read an uploaded file
<?php
$handle =
fopen($_FILES['userfile']['tmp_name'],"r");
while(!feof($handle))
{
$text = fgets($handle);
echo $text, "<br />";
}
fclose ($handle);
?>
112. 112
Form Buttons, Method 1
• You may want have multiple buttons on an
html form, the question how can you tell
which button(s) was (were) clicked by the
client
• First method, when a button is clicked on a
form put a description in a hidden field, then
read that field in the php server script. A
javascript will have to be included in the html
form
<form action="phpbuttons.php"
method="post" name = "form1">
<input type="hidden" name="button" />
<input type="button" value="b1"
onclick = "button1()" />
…
</form>
--------------- javascripts next slide
113. 113
Buttons Method 1
• the following javascript would have to be
included in the html form document
<script language="JavaScript">
<!--
function button1()
{
document.form1.Button.value = "b1";
form1.submit();
}
function button2()
{
document.form1.Button.value="b2";
form1.submit();
}
…
<!-- one function per button
</script>
--the receiving script then reads the hidden
field to determine which button was clicked
114. 114
Buttons Method 2
• The second method is to build multiple forms
on one html document. One form for each
button. Each button could then be built using
a submit button (there can only be one submit
button on a form). There would be a hidden
field in each form that contains the name of
the submit button for that form
One php server script can be specified in the
action attribute of each form. The identity of
the button can be read in the php server
script by reading the hidden field. Each
hidden field can be preset with the name of
the submit button in that form.
The problem with this approach is that if there
is extra data to be included on the form, it has
to be on all three forms. So, this method is
rarely used.
115. 115
Buttons Method 3
• You can pass data back to the server script
by using the value attribute of the submit
button.
You still must use three different forms, each
with a submit button with the same name. We
still have three forms, but the hidden field on
each form is not needed.
Each submit button would have a different
value, the string displayed on the face of the
button.
In the php server script we would access the
value as in:
<?php
if (isset($_POST["Button"]))
echo $_REQUEST["Button"], "<br />";
?>
why could you use both the $_POST and the
$_REQUEST super global arrays?
116. 116
Class Exercise
• Build a three part form
- the first document is a form that has a text
field that calls one php server script.
This script puts the contents of the text field
into another form and asks the user to
indicate how many times they want to
concatenate that entry together. It calls a
second php script.
The second server script performs the
concatenation and outputs back to the client
the original string entered and the
concatenated string. This script should
contain a function that is called multiple times
to do the concatenation, it should utilize a
static variable.
117. 117
Chapter 3 – Handling Strings and
Arrays
Dr M.Rani Reddy
118. 118
String Functions
• Lots of string functions are built into PHP.
There are string functions that sort, search,
trim, change case, and more in PHP. We’ll
look at many of these but not all. Most of the
important string functions are listed on pp 66-
67 in the text.
• trim, ltrim, rtrim
These functions trim whitespace characters,
usually blanks, from either or both ends of a
string variable
echo trim(" No worries. ", "n");
--No worries.
• print, echo
Displays a string.
print ("abc n"); print "var = $var";
echo "abc", "n";
note - inside double quotes, variables are
interpolated (they are replaced by their value
• strlen
returns the length of a string
$len = strlen("abcd"); (($len will be 4))
119. 119
String Functions (cont.)
• strpos
finds position of the first occurrence of a
target string inside a source string
$pos = strpos("ITEC 325","32");
--- $pos will have value 5
• strrev
reverses the characters in a string
$str = "abcd";
$newstr = strrev($str);
--- $newstr will have value "dcba"
• substr
returns a portion of a string
- first index is the start of the substring
- second index is the length of the substring
echo substr("ITEC 325", 5, 3);
• substr_replace
replace a target portion of a string with a new
substring
echo substr_replace("no way", "yes", 0,2);
-- what will be displayed?
120. 120
String Functions (cont.)
• strtolower, strtoupper
changes string to all lower or upper case
characters
$lowcas = strtolower("ABCdef");
-- $lowcas will have value "abcdef"
• strncmp
binary safe comparison of two strings for a
given number of characters, returns -1, 0, or 1
$ind = strncmp("ABC", "DEF", 3);
• strnatcmp
performs natural comparison of two strings
returns -1, 0, 1
$ind = strnatcmp("ABC", "def");
• we'll look at some more string functions that
work with arrays.
• there are many, many more string functions,
see table B-3 in your text
121. 121
Formatting Strings
• There are two string functions that are very
useful when you want to format data for
display, printf and sprintf.
printf (format [, args])
sprintf (format [,args])
The format string is composed of zero or
more directives: characters that are copied
directly to the result, and conversion
specifications. Each conversion specification
consists of a percent sign (%), followed by
one or more of these elements, in order:
- optional padding specifier indicating what
character should be used to pad the results to
the correct string size, space or a 0 character.
- optional alignment specifier indicating
whether the results should be left or right
justified.
- optional number, width specifier, specifying
how many minimum characters this
conversion should result in
122. 122
Formatting Strings (cont.)
- optional precision specifier that indicates
how many decimal digits should be displayed
for floating point numbers.
- a type specifier that says what type
argument the data should be treated as
Possible type specifiers are:
- percent character, no argument required
- integer presented as binary
- integer presented as the character with
that ASCII value
- integer presented as a signed decimal
- integer presented as unsigned decimal
- float presented as a float
- integer presented as octal
- string string
- integer presented as hex lowercase
- integer presented as hex uppercase
123. 123
Formatting Strings (cont.)
• printf ("I have %s apples and %s
oranges. n", 4, 56);
output is:
I have 4 apples and 56 oranges.
• $year = 2005; $month = 4; $day = 28;
printf("%04d-%2d-%02dn",
$year, $month, $day);
output is:
2005-04-28
• $price = 5999.99;
printf("$%01.2fn", $price);
output is:
$5999.99
124. 124
Formatting Strings (cont.)
• printf("%6.2fn", 1.2);
printf("%6.2fn", 10.2);
printf("%6.2fn", 100.2);
output is:
1.20
10.20
100.20
• $string = sprintf("Now I have %s apples and
%s oranges.n", 3, 5);
echo $string;
output is:
Now I have 3 apples and 5 oranges.
125. 125
Converting to & from Strings.
• Converting between string format and other
formats is a common task in web
programming.
To convert a float to a string:
$float = 1.2345;
echo (string) $float, "n";
echo strval($float), "n";
• A boolean TRUE is converted to the string "1"
and FALSE to an empty string "". An int or
float is converted to a string with its digits
and decimal points. The value NULL is
always converted to an empty string. A string
can be converted to a number, it will be a float
if it contains '.', 'e', or 'E'. PHP determines the
numeric value of a string from the initial part
of the string. If the string starts with numeric
data, it will use that. Otherwise, the value will
be 0.
126. 126
Converting to & from Strings (cont)
• Examples:
$number = 1 + "14.5";
echo "$numbern";
-- will output 15.5
$number = 1 + "-1.5e2";
echo "$numbern";
-- will output -149
$text = "5.0";
$number = (float) $text;
echo $number / 2.0, "n";
-- will output 2.5
$a = 14 + "dave14";
echo $a, "n";
-- will output
$a = "14dave" + 5;
echo $a, "n";
-- will output
127. 127
Creating Arrays
• Arrays are easy to handle in PHP because
each data item, or element, can be accessed
with an index value. Arrays can be created
when you assign data to them, array names
start with a $.
$students[1] = "John Smith";
this assignment statement creates an array
named $students and sets the element at
index 1 to "John Smith"
echo $students[1];
to add elements:
$students[2] = "Mary White";
$students[3] = "Juan Valdez";
you can also use strings as indexes:
$course["web_programming"] = 325;
$course["java_1"] = 120;
((sometimes called associative arrays))
128. 128
Creating Arrays (cont.)
• shortcut for creating arrays
$students[] = "John Smith";
$students[] = "Mary White";
$students[] = "Juan Valdez";
in this case $students[0] will hold "John
Smith" and $students[1] will hold "Mary
White", etc.
you can also create an array --
$students = array("John", "Mary", "Juan");
or like the above but specify indexes
$students = array (1 =>"John", 2=>"Mary",
3=>"Juan");
or --
$courses = array("web"=>325, "java1" =>
120);
the => operator lets you specify key/value
pairs
129. 129
Modifying Array Values
• current array values
$students[1] = "John Smith";
$students[2] = "Mary White";
$students[3] = "Juan Valdez";
$students[2] = "Kathy Jordan"; //modify
$students[4] = "Michael Xu"; // add new
$students[] = "George Lau"; // add new [5]
• looping through an array
for ($ct=1; ct<count($students); $ct++)
{
echo $students[ct], "<br />", "n");
}
• test what value the function count returns
when we have a sparse array!
130. 130
Modifying Arrays (cont.)
• consider:
$student[0] = "Mary"; // what's the prob???
$students[1] = "John";
$students[2] = "Ralph";
$students[0] = "";
this sets the element to null, but does not
remove the element from the array
to remove an element use the unset function
unset($students[0]);
without looping you can also display the
contents of an array with print_r
(print array)
print_r($students);
Array
{
[1] => John
[2] => Ralph
}
131. 131
foreach loop with Arrays
• useful to access all the elements of the array
without having to know what the indices are,
it has two forms:
foreach (array as $value)
{
statement(s)
}
foreach (array as $key => $value)
{
statement(s)
}
in the first, $value takes on each value in the
array in succession.
in the second form $key takes on the index
and $value takes the value of the array,
careful it's easy to confuse the two.
132. 132
Arrays & loops
• $students = array("White" => junior,
"Jones" => senior,
"Smith" => soph);
foreach ($students as $key => $val)
{
echo "Key: $key Value: $valn<br />";
}
• can also use the each function in a while loop
while (list($key, $val) = each ($students))
{
echo "Key: $key; Value: $valn<br />";
}
133. 133
Sorting Arrays
• $fruits[0] = "tangerine";
$fruits[1] = "apple";
$fruits[2] = "orange";
sort($fruits);
now $fruits[0] = "apple", etc.
rsort($fruits);
now $fruits[0] = "tangerine";
$fruits["good"] = "apple";
$fruits["better"] = "orange";
$fruits["best"] = "banana";
asort($fruits) results in apple, banana, orange
Note - sorted by value, but keys are
maintained
ksort($fruits) results in banana, orange, apple
sorts based on the indexes
134. 134
Navigating through Arrays
• PHP includes several functions for navigating
through arrays
consider an array has a pointer to the
"current" element, this could be any element
in the array
set the current pointer to the first element in
the array
reset($students);
echo current($students);
set the current pointer to the next or previous
element
next($students); prev($students);
echo next($students);
135. 135
Implode and Explode
• convert between strings and arrays by using
the PHP implode and explode functions
$cars = array("Honda", "Ford", "Buick");
$text = implode(",", $cars);
$text contains: Honda,Ford,Buick
• $cars = explode(",",$text);
now $cars -- ("Honda", "Ford", "Buick");
• use the list function to get data values from
an array
list ($first, $second) = $cars;
$first will contain "Honda"
$second will contain "Ford"
-- can also use the extract function
136. 136
Merging & Splitting Arrays
• $students[] = "Mary";
$students[] = "Ralph";
$students[] = "Karen";
$students[] = "Robert";
you can slice off part of an array:
$substudents = array_slice($students,1,2);
1 -- the array element you want to start
(offset)
2 - the number of elements (length)
$substudents now contains?
if the offset is negative, the sequence will be
measured from the end of the array. if the
length is negative, the sequence will stop that
many elements from the end of the array.
$newstudents = array("Frank", "Sheila");
merge the two arrays:
$mergestudents = array_merge($students,
$newstudents);
137. 137
Comparing Arrays
• PHP includes functions that will determine
which elements are the same in two arrays
and which are different.
$local_fruits = array("apple", "peach",
"orange");
$tropical_fruits = array("banana", "orange",
"pineapple");
$diff = array_diff($local_fruits,
$tropical_fruits);
(values in 1st array, not in second array)
$diff will contain -- apple, peach
$common = array_intersect($local_fruits,
$tropical_fruits);
$common will contain -- orange
can also work with associative arrays with
array_diff_assoc or array_intersect_assoc
138. 138
Array Functions
• delete duplicate elements in an array
$scores = array(65, 60, 70, 65, 65);
$scores = array_unique($scores);
now scores has (65, 60, 70)
• sum elements of an array
$sum = array_sum($scores);
now $sum has value 195
• the array_flip function will exchange an
array's keys and values
139. 139
Multidimensional Arrays
• $testscor['smith'][1] = 75;
$testscor['smith'][2] = 80;
$testscor['jones'][1] = 95;
$testscor['jones'][2] = 85;
have two indexes, so a two dimensional array
can use nested for loops to access and
process all the elements
foreach ($testscor as $outerkey => $singarr)
{
foreach($singarr as $innerkey => $val)
{
statements, average each students
test scores…
}
}
• Multidimensional sort - listing
• Multidimensional sort - execute
141. 141
Array Operators
• consider $aar and $bar are both arrays
$aar + $bar union
$aar == $bar TRUE, if have all same
elements
$aar === $bar TRUE, if same elements in
same order
$aar != $bar TRUE, not same elements
$aar <> $bar same as above
$aar !== $bar TRUE, not same elements in
same order
143. Topics
What is OOPS
Class & Objects
Modifier
Constructor
Deconstructor
Class Constants
Inheritance In Php
Magic Function
Polymorphism
Interfaces
Abstract Classes
Static Methods And Properties
Accessor Methods
Determining A Object's Class
144. What Is Oop ?
Object Oriented Programming (OOP) is the
programming method that involves the use of
the data , structure and organize classes of an
application. The data structure becomes an
objects that includes both functions and data. A
relationship between one object and other
object is created by the programmer
145. Classes
A class is a programmer
defined datatype which
include local fuctions as well
as local data.
Like a pattern or a blueprint
a oops class has exact
specifications. The
specification is the class' s
contract.
147. An object is a like a container that
contains methods and properties
which are require to make a certain
data types useful. An object’s
methods are what it can do and its
properties are what it knows.
Object
148. Modifier
In object oriented programming, some
Keywords are private and some are public in
class. These keyword are known as modifier.
These keywords help you to define how these
variables and properties will be accessed by the
user of this class.
149. Modifier
Private: Properties or methods declared as
private are not allowed to be called from
outside the class. However any method inside
the same class can access them without a
problem. In our Emailer class we have all these
properties declared as private, so if we execute
the following code we will find an error.
150. Modifier
<?
include_once("class.emailer.php");
$emobject = new Emailer("mranimca@rediff.com");
$emobject->subject = "Hello world";
?>
The above code upon execution gives a fatal error as shown below:
<b>Faprivate property emailer::$subject
in <b>C:OOP with PHP5Codesch1class.emailer.php</b> on line
<b>43</><br />
tal error</b>: Cannot access That means you can't access
151. Modifier
Public: Any property or method which is not
explicitly declared as private or protected is a
public method. You can access a public method
from inside or outside the class.
Protected: This is another modifier which has a
special meaning in OOP. If any property or
method is declared as protected, you can only
access the method from its subclass. To see
how a protected method or property actually
works, we'll use the following example:
152. Modifier
To start, let's open class.emailer.php file (the
Emailer class) and change the declaration of the
$sender variable. Make it as follows:
protected $sender
Now create another file name
class.extendedemailer.php with the following
code:
154. Constructor & Destructor
Constructor is Acclimated to Initialize the
Object.
Arguments can be taken by constructor.
A class name has same name as Constructor.
Memory allocation is done by Constructor
155. Constructor & Destructor
The objects that are created in memory, are
destroyed by the destructor.
Arguments can be taken by the destructor.
Overloading is possible in destructor.
It has same name as class name with tiled operator.
157. Class Constants
You can make constants in your PHP scripts
utilizing the predefine keyword to define
(constant name, constant value). At the same
time to make constants in the class you need to
utilize the const keyword. These constants
really work like static variables, the main
distinction is that they are read-only.
158. Class Constants
<?
class WordCounter
{
const ASC=1; //you need not use $ sign before Constants
const DESC=2;
private $words;
function construct($filename)
{
$file_content = file_get_contents($filename);
$this->words =
(array_count_values(str_word_count(strtolower
($file_content),1)));
159. Class Constants
}
public function count($order)
{
if ($order==self::ASC)
asort($this->words);
else if($order==self::DESC)
arsort($this->words);
foreach ($this->words as $key=>$val)
echo $key ." = ". $val."<br/>";
}
}
?>
161. Inheritance In Php
Inheritance is a well-known programming rule,
and PHP makes utilization of this standard in its
object model. This standard will influence the
way numerous objects and classes identify with
each other.
For illustration, when you extend a class, the
subclass inherits each public and protected
method from the guardian class. Unless a class
overrides those techniques, they will hold their
unique functionality
163. Magic Functions
There are some predefine function names
which you can’t use in your programme unless
you have magic functionality relate with them.
These functions are known as Magic Functions.
Magic functions have special names which
begine with two underscores.
165. Magic Functions
_ _construct()
Construct function is called when object is
instantiated. Generally it is used in php 5 for
creating constructor
_ _deconstruct()
It is the opposite of construct function. When
object of a class is unset, this function is called.
166. Magic Functions
_ _call()
When a class in a function is try to call an
accessible or inaccessible function , this method
is called.
_ _callStatic()
It is similar to callStatic() with only one
difference that is its triggered when you try to
call an accessible or inaccessible function in
static context.
167. Magic Functions
_ _get()
This function is triggered when your object try
call a variable of a class which is either
unavailable or inaccessible.
_ _set()
This function is called when we try to change to
value of a property which is unavailable or
inaccessible.
169. Polymorphism
The ability of a object, variable or function to
appear in many form is known as
polymorphism. It allows a developer to
programme in general rather than programme
in specific. There are two types of
polymorphism.
compile time polymorphism
run-time polymorphism".
170. Interfaces
There are some specific set of variable and functions
which can be called outside a class itself. These are
known as interfaces. Interfaces are declared using
interface keyword.
<?
//interface.dbdriver.php
interface DBDriver
{
public function connect();
public function execute($sql);
}
?>
172. Abstract Classes
A class which is declared using abstract keyword is
known as abstract class. An abstract class is not
implemented just declared only (followed by
semicolon without braces)
<?
//abstract.reportgenerator.php
abstract class ReportGenerator
{
public function generateReport($resultArray)
{
//write code to process the multidimensional result array and
//generate HTML Report
}
}
?
174. Static Methods & Properties
In object oriented programming, static keyword is
very crucial. Static properties and method acts as a
significant element in design pattern and application
design. To access any method or attribute in a class
you must create an instance (i.e. using new keyword,
like $object = new emailer()), otherwise you can't
access them. But there is a difference for static
methods and properties. You can access a static
method or property directly without creating any
instance of that class. A static member is like a global
member for that class and all instances of that class
175. Static Methods & Properties
<?
//class.dbmanager.php
class DBManager
{
public static function getMySQLDriver()
{
//instantiate a new MySQL Driver object and return
}
public static function getPostgreSQLDriver()
176. Static Methods & Properties
{
//instantiate a new PostgreSQL Driver object and
return
}
public static function getSQLiteDriver()
{
//instantiate a new MySQL Driver object and return
}
}
?>
177. Accessor Method
Accessor methods are simply methods that are
solely devoted to get and set the value of any class
properties. It's a good practice to access class
properties using accessor methods instead of
directly setting or getting their value. Though
accessor methods are the same as other methods,
there are some conventions writing them. There
are two types of accessor methods. One is called
getter, whose purpose is returning value of any
class property. The other is setter that sets a value
into a class property.
178. Accessor Method
<?
class Student
{
private $name;
private $roll;
More free ebooks : http://fast-file.blogspot.com
Chapter 2
[ 39 ]
public function setName($name)
{
$this->name= $name;
}
179. Accessor Method
public function setRoll($roll)
{
$this->roll =$roll;
}
public function getName()
{
return $this->name;
}
public function getRoll()
{
return $this->roll;
}
}
?>
180. Determining A Object's Class
public function setRoll($roll)
{
$this->roll =$roll;
}
public function getName()
{
return $this->name;
}
public function getRoll()
{
return $this->roll;
}
}
?>
182. 182
Opening a File: fopen
• We're able to create, modify, and access files
easily from PHP.
Files are used to store customer data, store
page hit counts, remember end-user
preferences, and a plethora of other things in
web applications.
• The fopen function opens a file for reading or
writing.
fopen (string filename, string mode,
[, int use_include_path
[, resource zcontext ]])
filename - name of the file including path
mode - how the file will be used read, write,
etc
use_include_path - optional parameter that
can be set to 1 to specify
that you want to search
for
the file in the PHP include
path
zcontext - not covered in these notes
183. 183
File Modes
• 'r' - open for reading only
• 'r+' - open for reading & writing
• 'w' - open for writing only, create file if
necessary
• 'w+' - open for reading and writing, create file
if necessary
• 'a' - open for appending, (start writing at
end of file)
• 'a+' - open for reading and writing
• 'x' - create and open for writing only, if file
already exists fopen will fail
• 'x+' - create and open for reading and
writing
• Note -------
different operating systems have different
line-ending conventions. When inserting a
line-break into a text file you need to use the
correct line-ending character(s). Windows
systems use rn, unix based systems use n.
PHP has a constant PHP_EOL which holds
the correct one for the system you are using.
184. 184
File Open Examples
• In Windows, you can use a text-mode
translation flag ('t'), which will translate n to
rn when working with the file. To use this
flag specify 't' as the last character of the
mode parameter, i.e.; 'wt'.
• Examples
-- open the file /home/file.txt for reading
$handle = fopen("/home/file.txt", "r");
# after this you'll refer to the file with the
variable $handle
-- open a file for writing
$handle = fopen("/home/wrfile.txt","w");
# the file will be created if it doesn't exist,
if it does exist you will overwrite whatever is
currently in the file
185. 185
File Open Examples
• open a file for binary writing
$handle = fopen("/home/file.txt", "wb");
• In Windows you should be careful to escape
any backslashes used in the path to the file
$handle = fopen("c:datafile.txt", "r");
• you can open files on another system
$handle = fopen("http://www.superduper.
com/file.txt", "r");
• can use ftp
$handle = fopen("ftp://user:password@
superduper.com/file.txt",
"r");
186. 186
Reading Lines of Text: fgets
• The fgets function reads a string of text from
a file.
fgets (resource handle [, int length]);
Pass this function the file handle to an open
file, and an optional length. Reading ends
when length - 1 bytes have been read, on a
newline (which is included in the return
value), or on encountering the end of file,
whichever comes first. If no length is
specified, the default length is 1024 bytes.
(file.txt below)
Here
is
the
file.
$handle = fopen("file.txt","r");
while (!feof($handle))
{
$text = fgets ($handle);
}
fclose($handle);
187. 187
Reading Characters: fgetc
• The fgetc function let's you read a single
character from an open file.
Here's
the file
contents.
$fhandle = fopen("file.txt", "r");
while ($char = fgetc($fhandle))
{
if ($char == "n")
{
$char = "<br />";
}
echo "$char";
}
fclose($fhandle);
188. 188
Binary Reading: fread
• Files don't have to be read line by line, you
can read a specified number of bytes (or until
the end-of-file is reached). The file is treated
as a simple binary file of bytes.
fread (resource handle, int length);
Bytes are read up to the length specified or
EOF is reached. On Windows systems, you
should open files for binary reading (mode
'rb') to work with fread. Adding 'b' to the
mode does no harm on other systems, it can
be included for portability.
$handle = fopen("file.txt","rb");
$text = fread($handle, filesize("file.txt");
// the filesize function returns the no. of bytes
// in the file.
you can convert line endings to <br />
$br_text = str_replace("n", "<br />", $text);
189. 189
Reading a Whole File: file_get_contents
• The file_get_contents function will read the
entire contents of a file into a string. No file
handle is needed for this function.
$text = file_get_contents("file.txt");
$br_text = str_replace("n","<br />",$text);
echo $br_text;
Careful with this function, for very large files,
it can be a problem since the entire file must
be memory resident at one time.
Parsing a File
To make it easier to extract data from a file,
you can format that file (using, for example,
tabs) and use fscanf to read your data from
the file.
In general -----
fscanf (resource handle, string format);
190. 190
Parsing a file: fscanf (cont.)
• This function takes a file handle, handle, and
format, which describes the format of the file
you're working with. You set up the format in
the same way as with sprintf, which was
discussed in Chapter 3. For example, say the
following data was contained in a file names
tabs.txt, where the first and last names are
separated by a tab.
George Washington
Benjamin Franklin
Thomas Jefferson
$fh = fopen("tabs.txt", "rb");
while ($names = fscanf($fh, "%st%sn"))
{
list($firstname,$lastname) = $names;
echo $firstname, " ", $lastname, "<br />";
}
fclose ($fh);
191. 191
Writing to a File: fwrite
• Write to a file with fwrite.
fwrite (resource fh, string str [, int length]);
The fwrite function writes the contents of str
to the file stream represented by fh. The
writing will stop after length bytes have been
written or the end of the string is reached.
fwrite returns the number of bytes written or
FALSE if there was an error. If you're working
on a Windows system the file must be opened
with 'b' included in the fopen mode
parameter.
$fh = fopen("text.txt","wb");
$text = "Herenisnthenfile.";
if (fwrite($fh, $text) == FALSE)
{
echo "Cannot write to text.txt.";
}
else {
echo "Created the file text.txt.";
}
fclose($fh);
192. 192
Appending to a File: fwrite
• In this case open the file for appending, using
the file mode 'a':
$fh = fopen("text.txt","ab");
Append this to text.txt:
And here is
more text.
$text = "nAnd here isnmore text.";
if (fwrite($fh, $text) == FALSE)
{
echo "Cannot write to text.txt.";
}
else {
echo "Appended to the file text.txt.";
}
fclose($fh);
193. 193
Writing a File at Once: file_put_contents
• This function writes a string to a file, and
here's how you use it in general:
file_put_contents (string filename, string data
[, int flags
[,resource context]]);
$text = "Herenisnthentext.";
if (file_put_contents("text.txt",$text) ==
FALSE)
{
echo "Cannot write to text.txt.";
}
else {
echo "Wrote to the file text.txt";
}
194. 194
Chapter 9 – Cookies, Sessions, FTP,
Email and More
Dr M.Rani Reddy
195. 195
PHP Sending Email
• The PHP installation has to include some
specifications for how to send email, in
particular the PHP initialization file must
specify the connections to the email system.
• At RU, this has been done.
• To send email in a PHP script use the mail
function.
Mail(string to, string subject, string message,
[,string additional_headers [,
string additional_parameters]])
This sends an email to the email address in
to, with subject subject and message
message. You can also set additional mail
headers and parameters to mail.
$result = mail(steve@ispname.com, “Web
mail”, $_REQUEST[“message”]);
**message is retrieved from html form
196. 196
PHP Email w/Headers (mailinput.php)
• Additional email headers like the following
may be specified.
cc (“carbon copy”)
bcc (“blind carbon copy”)
These are set with the additional_headers
parameter.
$headers .= “cc:” . $_REQUEST[“cc”] . “rn”;
$headers .= “bcc:” . $_REQUEST[“bcc”] .
“rn”;
$result = mail(“steve@chooseanisp.com”,
“Web mail”,
$_REQUEST[“message”],
$headers);
• Can also send email with attachments.
197. 197
PHP Cookies
• Cookies hold text that you can store on the
user’s computer and retrieve later. They are
set using the setcookie function.
setcookie parameters:
name - cookie name
value - value to be stored on the client
machine
expire - time the cookie expires, set with
PHP time function (1/1/70)
path - path on the server on which the
cookie will be available
domain - domain for which the cookie is
available
secure - indicates that the cookie should
only be transmitted via https.
198. 198
PHP Cookies
• Cookies are part of the HTTP headers sent to
the browser, and so they must be sent before
any other output from the PHP script. Calls to
this function must occur before any other
output from your script. This means calls to
setcookie must occur before any other output
including <html> and <head> tags. If some
output exists before calling this function,
setcookie may fail and return FALSE.
<?php
setcookie(“message”, “No worries.”);
?>
<html>
…
199. 199
Getting Cookies
• After a cookie is set, it won't be visible to
scripts until the next time a page is loaded.
The cookie is sent from the server machine,
so it won't be sent from the client to the
server until the next time a request is sent by
the client. Cookies are sent in the HTTP
headers to the server from the client, then
only if the request is for a page from the same
domain that the cookie came from.
After cookies are set, they can be accessed
on the next page load with $_COOKIE array.
Say a previous page set a cookie named
message. Then it will be in the global array
$_COOKIE. So, in the PHP script we have
only to access the $_COOKIE array, however,
we should check to see the cookie exists.
if (isset($_COOKIE['message']))
{
echo $_COOKIE['message'];
}
200. 200
COOKIE Arrays
• Cookie names can also be set as array names
and will be available to your PHP scripts as
arrays. For example:
setcookie("cookie[one]","no");
setcookie("cookie[two]","worries");
setcookie("cookie[three]","today.");
After these cookies have been set, they could
be read after the next request like this:
if (isset($_COOKIE['cookie']))
{
foreach ($_COOKIE['cookie'] as $data)
{
echo "$value <br />";
}
}
201. 201
Cookie Expiration Time
• You can also specify how long the cookie
should exist on the user's machine. The
cookie will be deleted when the user ends the
current browser session (which usually
means closing all browser windows). So,
normally we'll want to specify how long a
cookie should last by giving a value for the
expire parameter.
Normally, we use the time function which
returns current time, then add the number of
seconds we want the cookie to last.
setcookie("mycookie", $value, time() + 3600);
How long will this cookie last?
• Delete a Cookie
just set the cookie's value to "" and call
setcookie with the same parameters as the
cookie was set with. When the value
argument is set to an empty string, and all
other arguments match a previous call, then
the cookie will be deleted from the user's
machine.
202. 202
PHP Sessions
• When clients are working with various pages
in your web application, all the data in the
various pages is reset to its original values
when those pages are loaded. That means all
the data is reinitialized between accesses.
There are times when you want to retain data
from a single client longer. To do this you
can use cookies, hidden fields, or session
variables.
Sessions are designed to hold data on the
server. Each user is given a cookie with his
or her session ID, which means that PHP will
be able to reinstate all the data in each user's
session automatically, even over multiple
page accesses. If the user has cookies
turned off, PHP can encode the session ID in
the URL.
203. 203
PHP Sessions (cont.)
• Using sessions, you can store and retrieve
data by name. To work with a session, you
start by calling session_start. To store data
in the session, you use the $_SESSION array.
session_start();
$_SESSION['color'] = "blue";
in a separate page you might:
session_start();
$color = $_SESSION['color'];
Session behavior is affected by many settings
when PHP is installed. For example, session
variable life is limited to the number of
minutes specified for session.cache_expire,
which can only be set during the PHP install.
All data for a particular session will be stored
in a file in the directory specified by the
session.save_path item in the php.ini file. A
file for each session will be created.
205. 205
Functions
• In addition to the many built-in functions that
we've seen in PHP, user-defined functions
can be easily built
• User-defined functions
- it's the best way break code in manageble
sections
- when scripts are longer than 20-30
statements they should probably be broken
into functions
- functions limit variable scope
if you have a 2000 line script and you use a
variable named $counter at the beginning,
then you forget and use another variable
named $counter near the end, they will be the
same variable and unintended side effects
and bugs will result
- functions promote reusability
- functions improve reliability
206. 206
Creating a Function
• To define a function
function function_name([arg_list…])
{
}
• say all your web pages have a navigation bar
at the top
function nav_bar()
{
echo "<hr>";
echo "<center>";
echo "<a href='home.html'>Home</a>";
echo "<a href='map.html'>Site Map</a>";
echo "<a href='help.html'>Help</a>;
echo "</center>";
207. 207
Calling Functions
• Typically we include functions at the end of
code
<?php
echo "<h3>Welcome to my web page!</h3>";
…
nav_bar();
function nav_bar()
{
…
}
?>
209. 209
Passing Arrays to Functions
• Arrays can be passed to functions as
arguments
<?php
$fruits[0] = "apples";
$fruits[1] = "oranges";
array_echoer($fruits);
#call to function
function array_echoer($arr)
{
for ($ind=0;$index<count($arr);$ind++)
{
echo "Element $ind: ","$arr[$ind]", "n";
}
}
210. 210
Passing Arguments by Reference
• Pass-by-value is the default method of
passing argument values in PHP (a copy of
the value of the variable is made and stored in
local memory for the function). Meaning
what?
• What if we want to pass by reference, so if
changes are made to a value in the function
they are reflected in the calling program?
$string = "no ";
add_text($string);
echo $string;
function add_text(&$text)
{
$text .= "worries";
}
in this function the variable $string is passed
by reference, what would the output be if it
was not passed by reference?
211. 211
Variable-Length Argument Lists
• You can pass a variable number of arguments
to functions. For example, here's a function
named joiner that joins any number of strings
together.
joiner("No","worries");
joiner("Here's", "a", "longer", "string");
• There are three PHP functions to retrieve the
number of arguments and the value of each
argument passed to a function.
func_num_args -- returns the number of
arguments passed
func_get_arg -- returns a single argument
func_get_args -- returns all arguments in an
array.
212. 212
Varialble_Length Argument Lists (cont)
•
function joiner()
{
$text = "";
$arg_list = func_get_args();
for ($ct=0;$ct<func_num_args();$ct++)
{
$text .= $arg_list[$ct] . " ";
}
}
• Returning values from functions
just use the return statement
function square($val)
{
return ($val * $val);
}
call statement -- $sqval = square($num);
argpass.php
213. 213
Return Statements
• PHP does allow the use of multiple return
statements in a single function. When a
return statement is executed in a function,
execution of the function is over.
function check_temp($temp)
{
if ($temp > 65 && $temp<85)
{
return TRUE;
}
return FALSE;
}
Why is no else clause needed in this
function?
Is this good programming?
214. 214
Returning Arrays
• In PHP the return statement can return arrays
as well as scalar values.
function array_dbl($arr)
{
for ($ct=0;$ct<count($arr);$ct++)
{
$arr[$ct] *= 2;
}
return $arr;
}
to call --
$pricearray = array_db($pricearray);
• Exercise --
Implement an array doubler in php that
outputs an html document that shows the
original array values and the doubled array
values.
215. 215
Returning Lists
• Lists are another way to return multiple
values from a function.
function arraydbl($arr)
{
for ($ctr=0;$ctr<count($arr);$ct++)
{
$arr[$ctr] *= 2;
}
return $arr;
}
$loarr = array(2,4,6,8);
list($first, $second, $third) = arraydb($loarr);
• even if you only use the first few elements of
an array, it will work
• you can't return a list directly from a function
as in: return list($one, $two);
216. 216
Using Variable Scope
• breaking code into functions helps with:
testing & reliability,
code reuse,
documentation (maintainability),
and most definitely tends to reduce side
effects due to improper variable scope.
<?php
$val = 5;
echo "At script level, $val = ", $val, "<br />";
local_scope();
echo "after fn, $val = ", $val, "<br />";
function local_scope()
{
$val = 20000;
echo "in fn, $val = ", $val, "<br />";
}
?>
function variables are local scope --
217. 217
Global Access
• you can access script level (global) variables)
inside a function, but you must declare the
variable global
<?php
$val = 5;
echo "$val = ",$val, "<br />";
global_scope();
echo "scr level $val = ",$val,"<br />";
function global_scope()
{
global $val;
$val += 2;
echo "in fn $val =", $val, "<br />";
}
echo "scr level $val = ",$val,"<br />";
218. 218
Static Variables
• local variables in functions are reset to their
starting values each time the function is
called
you can have function variables retain their
values between function executions by
declaring a local variable as static
<?php
echo "count = ", counter(), "<br />";
echo "count = ", counter(), "<br />";
echo "count = ", counter(), "<br />";
echo "count = ", counter(), "<br />";
function counter()
{
static $countvar = 0;
$countvar++;
return $countvar;
}
?>
219. 219
Variable Functions
• a variable can hold the name of a function,
the function can be called by including
parentheses after variable. this allows the
program to determine which function is called
at run time
$fn_var = "apples";
$fn_var();
$fn_var = "oranges";
$fn_var();
function apples()
{
…
}
function oranges()
{
…
}
-- think about determining which function to
call based on input
220. 220
Conditional & Sub Functions
• some functions may be defined inside an if
statement or in some other conditional clause
in this case, since PHP is an interpreted
language, you have to make sure the
conditional statement is executed before the
function is executed
• functions can be nested in PHP
remember, like conditional functions, the
internal (nested function) doesn't exist until
the enclosing function is executed
<?php
function enclosfn()
{ echo "Hello";
function created_function()
{ echo "Hello from created"; }
}
enclosfn();
created_function();
?>
221. 221
Include Files
• include files allow you to reuse functions
stored in separate files
example define some constants in a separate
file
<?php
// file is constants.php
define ("pi",3.14159);
define ("e",2.71828);
?>
<?php
// file is app.php
include("constants.php");
echo "value for pi: ", pi, "<br />";
?>
login functions that are used by a number of
applications, database login values and
passwords, etc.
222. 222
Errors Returned from Functions
• if there's been an error in a function, that
function returns a value of FALSE
intentionally. you can also write functions
that will return false if there's an error
function reciprocal($val)
{
if ($val != 0)
{
return 1/$val;
}
else
{
return FALSE;
}
}
one way of handling a return value of FALSE
is to use the PHP die function
$filename = "nonfile";
$file = fopen($filename, "r")
or die("Cannot open file");