PHP
1
PHP
Topics
 Introducing Three-Tier Architectures
 Introducing PHP









2
Basic Features
Variables and Constants
Expressions and Operators
Type Conversion
Conditions and Branches
Loops
Arrays
User-Defined Functions
Objects
PHP
Introducing Three-Tier Architectures
 Most web database applications bring together
the Web and databases through three layers of
application logic naming three-tier architecture:
 At the base of an application is the database tier,
consisting of the database management system that
manages the database containing the data users
create, delete, modify, and query.
 Built on top of the database tier is the complex
middle tier, which contains most of the application
logic and communicates data between the other tiers.
 On top is the client tier, usually web browser software
that interacts with the application.
3
Figure 1-1.
PHP
Introducing Three-Tier Architectures
4
PHP
Introducing Three-Tier Architectures
 Client Tier
 The client tier in the three-tier architecture model is
usually a web browser.
 Web browser software:
» Processes and displays HTML resources
» Issues HTTP requests for resources
» Processes HTTP responses
 There are significant advantages to using a web
browser as the thin-client layer
» Easy deployment
» Support on a wide range of platforms
5
PHP
Introducing Three-Tier Architectures
 Middle Tier
 In most three-tier web database systems, the
majority of the application logic is in the middle
tier.
» it drives the structure and content of the data
displayed to the user
» it processes input from the user as it is formed into
queries on the database to read or write data.
» It also adds state management to the HTTP protocol.
» It integrates the Web with the database management
system.
 the components of the middle tier are
6
» a web server
» a web scripting language
» the scripting language engine
PHP
Introducing Three-Tier Architectures
 The PHP scripting language is used as the
middle-tier scripting language.
 PHP has emerged as a component of many
medium- and large-scale web database
applications.
 there are many reasons that make PHP a good
choice, including:
7
» PHP is open source, meaning it is entirely free.
» One or more PHP scripts can be embedded into
static HTML files and this makes client-tier
integration easy.
» Fast execution of scripts.
» Platform and operating-system flexibility.
» PHP is suited to complex systems development. It is
a fully featured programming language.
PHP
Introducing Three-Tier Architectures
 Database Tier
 The database tier is the base of a web database
application.
 In a three-tier architecture application, the
database tier manages the data.
 In many web database applications, data
management are provided by a RDBMS system,
and the data stored in a relational database.
 The MySQL RDBMS is used to manage data.
 Like PHP, MySQL is open source software.88
8
PHP
Introducing PHP
 PHP is similar to high-level languages such as
C, Perl, Pascal, FORTRAN, and Java, and
programmers who have experience with any of
these languages should have little trouble
learning PHP.
 The current version of PHP is PHP4, which we
call PHP. The current release at the time of
writing is 4.0.6.
 PHP is a recursive acronym that stands for PHP:
Hypertext Preprocessor.
9
PHP
Introducing PHP
 PHP is a scripting language that's usually
embedded or combined with HTML and has
many excellent libraries that provide fast,
customized access to DBMSs.
 It's an ideal tool for developing application logic
in the middle tier of a three-tier application.
Example 2.1
Output
10
PHP
Basic Features
 several features of PHP:
 The begin and end script tags are <?php and ?> or,
more simply, just <? and ?>. The longer begin tag
style <?php avoids conflicts with other processing
instructions that can be used in HTML.
 Other begin and end tag styles can also be
configured, such as the HTML style that is used with
JavaScript or other embedded scripts: <script
language="PHP"> and </script>.
11
PHP
Basic Features
 White space has no effect, except to aid readability
for the developer. For example, the script could have
been written succinctly as <? php echo "Hello,
world";?> with the same effect. Any mix of spaces,
tabs, carriage returns, and so on in separating
statements is allowed.
 A PHP script is a series of statements, each
terminated with a semicolon. Our simple example
has only one statement: echo "Hello, world";.
 A PHP script can be anywhere in a file and
interleaved with any HTML fragment. While Example
2-1 contains only one script, there can be any
number of PHP scripts in a file.
12
PHP
Basic Features
 When a PHP script is run, the entire script including
the start and end script tags <?php and ?> is
replaced with the output of the script.
13
PHP
Basic Features
 The freedom to interleave any number of scripts
with HTML is one of the most powerful features
of PHP.
Example 2.2
Output
14
PHP
Basic Features
 Comments
// This is a one-line comment
# This is another one-line comment style
/* This is how you
can create a multi-line
comment */
15
PHP
Basic Features
 Outputting data with echo and print
echo "Hello, world";
// print works just the same
print "Hello, world";
// numbers can be printed too
echo 123;
// So can the contents of variables
echo $outputString;
 The difference between print and echo is that echo
can output more than one argument:
echo "Hello, ", "world";
16
PHP
Basic Features
 There is also a shortcut that can output data. The
following very short script outputs the value of the
variable $temp:
<?=$temp; ?>
 The print and echo statements are also often seen
with parentheses:
echo "hello";
// is the same as
echo ("hello");
 Parentheses make no difference to the behavior of
print. However, when they are used with echo, only
one output parameter can be provided.
 more complex output is printf
17
PHP
Basic Features
 String literals
 PHP can create double- and single-quoted string
literals. If double quotation marks are needed as part
of a string, the easiest approach is to switch to the
single-quotation style:
echo 'This works';
echo "just like this.";
 One of the convenient features of PHP is the ability to
include the value of a variable in a string literal.
18
$number = 45;
$vehicle = "bus";
$message = "This $vehicle holds $number people";
// prints "This bus holds 45 people"
echo $message;
PHP
Variables and Constants
 Variables
 Variables in PHP are identified by a dollar sign
followed by the variable name.
 Variables don't need to be declared.
 they have no type until they are assigned a value.
$var = 15;
$var = "Sarah the Cat";
 Variable names are case-sensitive in PHP, so
$Variable, $variable, $VAriable, and $VARIABLE are
all different variables.
19
PHP
Variables and Constants
 Types
 PHP has four scalar types:
»Boolean
$variable = false;
$test = true
»Float
$var2 = 6.0;
$var3 = 1.12e3;
»Integer
$var1 = 6;
»String
$variable = "This is a string";
20
PHP
Variables and Constants
 two compound types:
» Array
» Object
21
PHP
Variables and Constants
 Constants
define("pi", 3.14159);
echo pi;
22
PHP
Expressions and Operators
// Assign a value to a variable
$var = 1;
// Sum integers to produce an integer
$var = 4 + 7;
// Subtraction, multiplication, and division
// that might have a result that is a float or
// an integer, depending on the initial value of $var
$var = (($var - 5) * 2) / 3;
23
PHP
Expressions and Operators
// These all add 1 to $var
$var = $var + 1;
$var += 1;
$var++;
// And these all subtract 1 from $var
$var = $var - 1;
$var -= 1;
$var--;
24
PHP
Expressions and Operators
25
// Double a value
var = $var * 2;
$var *= 2;
// Halve a value
$var = $var / 2;
$var /= 2;
// These work with float types too
$var = 123.45 * 28.2;
String assignments and expressions are similar:
1352172
// Assign a string value to a variable
$var = "test string";
PHP
Expressions and Operators
// Concatenate two strings together
// to produce "test string"
$var = "test" . " string";
// Add a string to the end of another
// to produce "test string"
$var = "test";
$var = $var . " string";
// Here is a shortcut to add a string to
// the end of another
$var .= " test";
26
PHP
Type Conversion
 PHP provides several mechanisms to allow
variables of one type to be considered as
another type.
 Variables can be explicitly converted to another
type with the following functions:
 string strval(mixed variable)
 integer intval(mixed variable)
 float floatval(mixed variable)
 The function settype(mixed variable, string type)
can explicitly set the type of variable to type,
where type is again one of array, boolean, float,
27 integer, object, or string.
PHP
Type Conversion
 PHP supports type-casting in much the same way as C.
By placing the type name in parentheses in front of a
variable, PHP converts the value to the desired type:
(int) $var
(bool) $var
(float) $var, (double) $var or (real) $var
(string) $var
(array) $var
(object) $var
28
Cast to integer
Cast to Boolean
Cast to float
Cast to string
Cast to array
Cast to object
PHP
Conditions and Branches
 if...else Statement
if ($var < 5)
echo "Variable is very small";
elseif ($var < 10)
echo "Variable is small";
elseif ($var < 20)
echo "Variable is big";
elseif ($var < 30)
echo "Variable is very big";
 can use == <= >= inside expressions
 can use || && ! inside expressions
29
PHP
Conditions and Branches
 switch Statement
switch ($menu)
{
case 1:
echo "You picked one";
break;
case 2:
echo "You picked two";
break;
default:
echo "You picked another option";
}
30
PHP
Conditions and Branches
 Conditional Expressions
 There is a new operator in PHP4, the is-identical
operator ===. This isn't found in other languages
and returns true only if the expression evaluates
as equal and the arguments are of the same type.
31
// Returns true, since both are integers and equal
if (5 === 5)
echo "Same types and value";
// Returns false, since there are mixed types
// (5.0 is a float, and 5 is an integer)
if (5.0 === 5)
echo "This never prints!";
// The normal equality check would return true
if (5.0 == 5)
echo "This always prints";
PHP
Loops
 While
$counter = 1;
while ($counter < 11)
{
echo $counter;
echo " ";
// Add one to $counter
$counter++;
}
32
PHP
Loops
 do...while
$counter = 1;
do
{
echo $counter;
echo " ";
$counter++;
} while ($counter < 11);
33
PHP
Loops
 for
for($counter=1; $counter<11; $counter++)
{
echo $counter;
echo " ";
}
34
PHP
Loops
 Foreach
 The foreach statement was introduced in PHP4
and provides a convenient way to iterate through
the values of an array.
// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);
// Convert an array of centimeter lengths to inches
foreach($lengths as $cm)
{
$inch = (100 * $cm) / 2.45;
echo "$cm centimeters = $inch inches\n";
}
35
Example 2.3
Output
PHP
Arrays
 Arrays in PHP are sophisticated and more
flexible than in many other high-level languages.
 An array is an ordered set of variables, in which
each variable is called an element.
 Arrays can be either numbered or associative,
which means that the elements of an array can
be accessed by a numeric index or by a textual
string, respectively.
 In PHP, an array can hold scalar values—
integers, Booleans, strings, or floats—or
compound values —objects and even other
36
arrays, and can hold values of different types.
PHP
Arrays
 Creating Arrays
$numbers = array(5, 4, 3, 2, 1);
$words = array("Web", "Database", "Applications");
// Print the third element from the array
// of integers: 3
echo $numbers[2];
// Print the first element from the array
// of strings: "Web"
echo $words[0];
37
PHP
Arrays
 Associative arrays
 An associative array uses string indexes—or
keys—to access values stored in the array. An
associative array can be constructed using array(
).
$array = array("first"=>1, "second"=>2, "third"=>3);
// Echo out the second element: prints "2"
echo $array["second"];
38
PHP
Arrays
 Heterogeneous arrays
 The values that can be stored in a single PHP
array don't have to be of the same type; PHP
arrays can contain heterogeneous values.
$mixedBag = array("cat", 42, 8.5, false);
var_dump($mixedBag);
39
PHP
Arrays
 Multidimensional arrays
 PHP arrays can also hold other arrays creating
multidimensional arrays.
Example 2.4
40
PHP
Arrays
 Using foreach Loops with Arrays
 The foreach statement was specifically introduced
in PHP4 to make working with arrays easier.
// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);
// Convert an array of centimeter lengths to inches
foreach($lengths as $cm)
{
$inch = $cm / 2.54;
echo "$cm centimeters = $inch inches\n";
}
41
PHP
Arrays
 Using Array Pointers
 PHP maintains an internal index that points to the
current element in the array.
$a = array("a", "b", "c", "d", "e", "f");
echo current($a ); // prints "a
// Array ( [1]=> a [value]=> a [0]=> 0 [key]=> 0 )
print_r each($a);
// Array ( [1]=> b [value]=> b [0]=> 1 [key]=> 1 )
print_r each($a);
// Array ( [1]=> c [value]=> c [0]=> 2 [key]=> 2 )
print_r each($a);
echo current($a ); // prints "d"
42
PHP
Arrays
 Other functions that use the array's internal
pointer are:






43
end( )
next( )
prev( )
reset( )
key( )
list( )
PHP
Arrays
 Basic Array Functions
 The count( ) function returns the number of
elements in the array var:
integer count(mixed var)
 The maximum and minimum values can be found
from an array numbers with max( ) and min( ):
number max(array numbers)
number min(array numbers)
44
PHP
Arrays
 Finding values in arrays with in_array( ) and
array_search( )
 The in_array( ) function returns true if an array
haystack contains a specific value needle:
boolean in_array(mixed needle, array haystack [,
boolean strict])
 The array_search( ) function works the same way
as the in_array( ) function, except the key of the
matching value needle is returned rather than the
Boolean value true:
mixed array_search(mixed needle, array haystack [,
boolean strict])
45
PHP
Arrays
 Reordering elements in arrays with
array_reverse( )
 The array_reverse( ) function creates a new array
by reversing the elements from a source array:
array array_reverse(array source [, bool
preserve_keys])
46
PHP
Arrays
 Sorting Arrays
 The simplest array-sorting functions are sort( )
and rsort( ), which rearrange the elements of the
subject array in ascending and descending order.
sort(array subject [, integer sort_flag])
rsort(array subject [, integer sort_flag])
47
PHP
User-Defined Functions
 Functions provide a way to group together
related statements into a cohesive block.
 For reusable code, a function saves duplicating
statements and makes maintenance of the code
easier.
Example 2-6
48
PHP
User-Defined Functions
function heading($text, $headingLevel)
{
switch ($headingLevel)
case 1:
$result = "<h1>" . ucwords($text) . "</h1>";
break;
case 2:
$result = "<h2>" . ucwords($text) . "</h2>";
break;
default:
$result = "<p><b>" . ucfirst($text) . "</b>";
return($result);
}
$test = "user defined functions";
echo heading($test, 2);
49
PHP
User-Defined Functions
 Variable Scope
 Variables used inside a function are different from
those used outside a function. The variables used
inside the function are limited to the scope of the
function.
function doublevalue($var)
{
$temp = $var * 2;
}
$variable = 5;
doublevalue($variable);
echo "\$temp is: $temp";
50
no value for $temp.
PHP
User-Defined Functions
 If you want to use a value that is local to a
function elsewhere in a script, the easiest way to
do so is to return the value of the variable.
function doublevalue($var)
{
$returnVar = $var * 2;
return($returnVar);
}
$variable = 5;
$temp = doublevalue($variable);
echo "\$temp is: $temp";
$temp is: 10
51
PHP
User-Defined Functions
 Global variables
 The global statement declares a variable within a
function as being the same as the variable that is
used outside of the function.
function doublevalue( )
{
global $temp;
$temp = $temp * 2;
}
$temp = 5;
doublevalue( );
echo "\$temp is: $temp";
52
$temp is: 10
PHP
User-Defined Functions
 How Variables Are Passed to Functions
 By default, variables are passed to functions by
value, not by reference.
function doublevalue($var)
{
$var = $var * 2;
}
$variable = 5;
doublevalue($variable);
echo "\$variable is: $variable";
$variable is: 5
53
PHP
User-Defined Functions
 An alternative to returning a result or using a
global variable is to pass a reference (using &$var
in the declaration) to a variable as an argument
to the function. This means that any changes to
the variable within the function affect the original
variable.
function doublevalue(&$var)
{
$var = $var * 2;
}
$variable = 5;
doublevalue($variable);
echo "\$variable is: $variable";
?>
54
$variable is: 10
PHP
User-Defined Functions
 PHP allows functions to be defined with default
values for arguments. A default value is simply
supplied in the argument list using the = sign.
55
function heading($text, $headingLevel = 2)
{
switch ($level)
case 1:
$result = "<h1>" . ucwords($text) . "</h1>";
break;
case 2:
$result = "<h2>" . ucwords($text) . "</h2>";
break;
default:
$result = "<p><b>" . ucfirst($text) . "</b>";
return($result);
}
$test = "user defined functions";
echo heading($test);
PHP
Objects
 PHP has limited support for object-oriented
programming and allows programmers to define
their own classes and create object instances of
those classes.
56
PHP
Objects
 Classes and Objects
 A class defines a compound data structure made
up of member variables and a set of functions that
operate with the specific structure.
Example 2.7
 To use the data structures and functions defined
in a class, an instance of the class—an object—
needs to be created.
 objects are created using the new operator.
$aCounter = new Counter;
Example 2.8
57
PHP
Objects
 Inheritance
 One of the powerful concepts in object-oriented
programming is inheritance.
 Inheritance allows a new class to be defined by
extending the capabilities of an existing base
class.
 PHP allows a new class to be created by
extending an existing class with the extends
keyword.
Example 2.9
58
PHP
Objects
» The power of inheritance doesn't come from
simply reusing code. Objects created from the
extended class can be used as if they were
created from the existing base class. This ability
to use an object as if it were an instance of the
base class is known as polymorphism.
59
Descargar

Slide 1