Module 3 Ref
Module 3 Ref
Page 1
CST463 - WEB PROGRAMMING
Page 2
Module 2 (CO3, Cognitive Knowledge Level: Apply)
Page 3
PHP Language Structure
Page 4
Introduction
► Rasmus Lerdorf developed PHP in 1994.
► A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
► A PHP script can be placed anywhere in the document.
► A PHP file normally contains HTML tags, and some PHP scripting code.
►PHP code is executed on the server, generating HTML which is then sent to the client.
►The client would receive the results of running that script, but would not know what the
underlying code was.
►PHP is compatible with almost all servers used today (Apache, IIS, etc.). PHP is easy to
learn and runs efficiently on the server side
► PHP is FREE to download from : www.php.net
Page 5
Introduction to PHP
Page 6
Three-tier web-based application
Page 7
Three-tier web-based application
► The bottom tier (also called the data tier or the information tier) maintains the
application’s data. This tier typically stores data in a relational database management
system (RDBMS)
► The middle tier implements business logic, controller logic and presentation logic to
control interactions between the application’s clients and its data. The middle tier
acts as an intermediary between data in the information tier and the application’s
clients. The middle-tier controller logic processes client requests (such as requests to
view a product catalog) and retrieves data from the database
► The top tier, or client tier, is the application’s user interface, which gathers input and
displays output. Users interact directly with the application through the user
interface, which is typically a web browser or a mobile device
Page 8
Client-Side Scripting versus Server-Side Scripting
► Client-side scripting with JavaScript can be used to validate user input, to interact
with the browser, to enhance web pages, and to add client/server communication
between a browser and a web server.
► Client-side scripting does have limitations, such as browser dependency; the browser
or scripting host must support the scripting language and capabilities.
► client-side scripts can be viewed by the client using the browser’s source-viewing
capability
► server-side scripts, often generate custom responses for clients
► Server-side scripting languages have a wider range of programmatic capabilities
than their client-side equivalents.
► Server-side scripts also have access to server-side software that extends server
functionality—Microsoft web servers use ISAPI (Internet Server Application Program
Interface) extensions and Apache HTTP Servers use modules.
Page 9
Accessing Web Server
► To request documents from web servers, users must know the hostnames on which
the web server software resides.
► Users can request documents from local web servers (i.e., ones residing on users’
machines) or remote web servers (i.e., ones residing on different machines).
► Local web servers can be accessed through your computer’s name or through the
name localhost
► localhost—a hostname that references the local machine and normally translates to
the IP address 127.0.0.1 (known as the loopback address).
Page 10
Installing to PHP
MAMP.
http://www.mamp.info/en/index.html
Page 11
PHP Language Structure
► PHP: “Hypertext Preprocessor”
► Originally, PHP was an acronym for Personal Home Page
► web development tool (not case sensitive)and can be embedded into HTML
► PHP scripts are executed on the server and is a case sensitive language . but PHP
function names are case in-sensitive
► PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
►PHP runs on different platforms (Windows, Linux, Unix, etc.)
Page 12
Building blocks of PHP
► Variables ► Variables
► Data Types ► All variable names in PHP begin with dollar signs ($)
► Operators and Expressions ► a letter or an underscore followed by any number
► Constants (including zero) of letters, digits, or underscores.
► PHP variable names are case sensitive.
► Assigned by value
► $foo = "Bob"; $bar = $foo;
Page 13
Building blocks of PHP
► Variables
► Line 5 outputs the value of variable $name by calling function print. The value of
$name is printed, not the string "$name".
► When a variable is encountered inside a doublequoted ("") string, PHP interpolates
the variable
► . All operations of this type execute on the server before the HTML5 document is
sent to the client
► PHP variables are loosely typed—they can contain different types of data (e.g.,
integers, doubles or strings) at different time
Page 14
Building blocks of PHP
► Global Variables
► In PHP global variables must be declared global inside
a function if they are going to be used in that function.
► The above script will output 3. By declaring $a and $b global within the function, all
references to either variable will refer to the global version. There is no limit to the
number of global variables that can be manipulated by a function.
Page 15
Building blocks of PHP
► Super Global Variables ► The PHP superglobal variables are:
► Super global variables are built-in ► $GLOBALS
variables that are always available in ► $_SERVER
all scopes.
► $_REQUEST
► Some predefined variables in PHP are
► $_POST
"superglobals", which means that they
are always accessible, regardless of ► $_GET
scope - and you can access them from ► $_FILES
any function, class or file without ► $_ENV
having to do anything special. ► $_COOKIE
► $_SESSION
Page 16
Building blocks of PHP
► second way to access variables from the
global scope is to use the special PHP-
defined $GLOBALS array
► The $GLOBALS array is an associative array
with the name of the global variable being
the key and the contents of that variable
being the value of the array element.
► $b is a variable present within the
$GLOBALS array, it is also accessible from
outside the function!
Page 17
Superglobal variables
► $GLOBALS- PHP super global variable which is used to access global variables
from anywhere in the PHP script
► $_SERVER is a PHP super global variable which holds information about
headers, paths, and script locations.
► $_REQUEST is a PHP super global variable which is used to collect data after
submitting an HTML form.
► $_POST is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="post". $_POST is also widely used to
pass variables.
► $_GET is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="get".$_GET can also collect data sent
in the URL.
Page 18
Building blocks of PHP
► Variables
► Data Types
► Operators and Expressions
► Constants
Reserved Words
Page 19
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Data Types Constants
Page 20
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Data Types Constants
► PHP has four scalar types: Boolean, integer, double, and string; two compound
types, array and object; and two special types, resource and NULL
1 Integer Type
► PHP has a single integer type, named integer. (corresponds to the long type of C)
► In most cases, this is 32 bits, or a bit less (not fewer) than ten decimal digits.
2 Double Type
► PHP's double type corresponds to the double type of C and its successors.
► Double literals can include a decimal point, an exponent, or both. The exponent
has an E or an e
► Floating point numbers (also known as "floats", "doubles", or "real numbers") can
be specified using any of the following syntaxes:
Page 21
Order of Precedence of Style Sheet
3.String Type
► Characters in PHP are single bytes. no character type.
► A single character data value is represented as a string of length 1.
► String literals with either single (') or double quotes (")
► In single-quoted string literals, escape sequences, such as \n, are not
recognized and the values of embedded variables are not substituted
► ‘The sum is :$sum’ exactly as it is typed.
► In double-quoted string literals, escape sequences are recognized, and
embedded variables are replaced by their current values.
$sum=10;
print “The sum : $sum”;
o/p :The sum : 10
Page 22
Variables
Building blocks of PHP Data Types
Operators & Expressions
Constants
4.Boolean Type
► The only two possible values for the Boolean type are TRUE and FALSE, both of
which are case insensitive.
► It is used in control structure like the testing portion of an if statement.
Page 23
Variables
Building blocks of PHP Data Types
Operators & Expressions
Constants
//Result of the equal operator is a Boolean
<?php
//Result of the condition is a Boolean
$height=100; <?php
$width=50;
$height=100;
$width=50;
if ($width == 0) if ($width)
{
{ echo "The area of the rectangle is".$height*$width;
echo "The width needs to be a non-zero }
else
number"; {
} echo "The width needs to be a non-zero number";
}
?> ?>
Page 24
Variables
Determining data types Data Types
Operators & Expressions
Constants
► PHP has several useful functions for determining the type of a variable.
► is_array() True if variable is an array.
► is_bool() True if variable is a bool.
► is_float(), is_double(), is_real() True if variable is a float.
► is_int(), is_integer(), is_long() True if variable is an integer.
► is_null() True if variable is set to null.
► is_numeric() True if variable is a number or numeric string.
► is_scalar() True if variable is an int, float, string, or bool.
► is_object() True if variable is an object.
► is_resource() True if variable is a resource.
► is_string() True if variable is a string.
Page 25
Variables
changing data types Data Types
Operators & Expressions
Constants
► PHP includes both implicit and explicit type conversions.
► Implicit type conversions are called coercions
► The context can cause a coercion of the type of the value of the expression.
► Whenever a numeric value appears in string context, the numeric value is coerced
to a string.
► whenever a string value appears in numeric context, the string value is coerced to
a numeric value. If the string contains a period, an e, or an E, it is converted to
double; otherwise, it is converted to an integer.
► When a double is converted to an integer, the fractional part is dropped;
rounding is not done
Page 26
Variables
changing data types Data Types
Operators & Expressions
Constants
► Explicit type conversions can be specified in three ways.
► Using the syntax of C, an expression can be cast to a different type. The cast is a
type name in parentheses preceding the expression. For example, if the value of
$sum is 4 . 777, the following produces 4: (int)$sum
► Another way to specify explicit type conversion is to use one of the functions
intval(), doubleval(), or strval(). For example, if $sum is still 4.77 7, the following
call returns 4:
intval($sum)
► The third way to specify an explicit type conversion is the settype() function,
which takes two parameters: a variable and a string that specifies a type name.
For example, if $sum is still 4 . 777, the following statement converts the value of
$sum to 4 and its type to integer: settype($sum, "integer");
Page 27
Variables
changing data types with settype() Data Types
Operators & Expressions
Constants
► The settype() function converts a variable to a specific type.
► Syntax: settype(variable, type);
<?php
$a = "32"; // string
settype($a, "integer"); // $a is now integer
$b = 32; // integer
settype($b, "string"); // $b is now string
$c = true; // boolean
settype($c, "integer"); // $c is now integer (1)
?>
Page 28
Variables
changing data types by casting Data Types
Operators & Expressions
Constants
► We can cast following data type variable in PHP
► (int), (integer) - cast to integer
► (bool), (boolean) - cast to boolean
► (float), (double), (real) - cast to float
► (string) - cast to string
► (array) - cast to array
► (object) - cast to object
► (unset) - cast to NULL (PHP 5)
Page 29
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Operators &expressions Constants
► PHP has the usual (for C-based programming languages) collection of arithmetic operators (+, -,
*, /, %, ++, and --)
► If either operand is a double, the operation is double and a double result is produced
► Operators are used to perform operations on variables and values.
► PHP divides the operators in the following groups:
► Arithmetic operators
► Assignment operators
► Comparison operators
► Increment/Decrement operators
► Logical operators
► String operators
► Array operators
► Conditional assignment operators
Page 30
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Operators &expressions Constants
Page 31
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Operators &expressions Constants
Page 32
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Operators &expressions Constants
Page 33
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Operators &expressions Constants
Page 34
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Operators &expressions-predefined Functions Constants
Page 35
Building blocks of PHP
► Operators
Page 36
floor(),ceil()
► The floor() function rounds a number DOWN to the nearest integer, if necessary.
<?php
echo(floor(0.60) . "<br>"); //0
echo(floor(0.40) . "<br>");//0
echo(floor(5) . "<br>");//5
echo(floor(5.1) . "<br>");//5
echo(floor(-5.1) . "<br>");//-6
echo(floor(-5.9));//-6
echo (ceil(0.70)); //1
echo(ceil(-4.1));//-4
echo(ceil(6.2));//7
echo(round(0.70878, 2)); //0.71?>
► ceil():To round a number UP to the nearest integer use the ceil() function.
► round(): To round a floating-point number, use the round() function
Page 37
rand()
► The rand() function generates a random integer.
► If you want a random integer between 10 and 100 (inclusive), use rand (10,100).
<!DOCTYPE html>
<html>
<body>
<?php
echo(rand() . "<br>");
echo(rand() . "<br>");
echo(rand(10,100));
?>
</body>
</html>
Page 38
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Constants Constants
► A constant is a name or an identifier for a simple value. A constant value cannot
change during the execution of the script. By default, a constant is case-sensitive.
By convention, constant identifiers are always uppercase.
► A constant name starts with a letter or underscore, followed by any number of
letters, numbers, or underscores.
► If you have defined a constant, it can never be changed or undefined.
► To define a constant you have to use define() function and to retrieve the value
of a constant, you have to simply specifying its name
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line?>
Page 39
Variables
Building blocks of PHP Data Types
Operators & Expressions
► Constants Constants
► Only scalar data (boolean, integer, float and string)
can be contained in constants.
► Differences between constants and variables are
► There is no need to write a dollar sign ($) before a
constant, where as in Variable one has to write a
dollar sign.
► Constants cannot be defined by simple assignment,
they may only be defined using the define() function.
► Constants may be defined and accessed anywhere
without regard to variable scoping rules.
► Once the Constants have been set, may not be
redefined or undefined.
Page 40
Echo and Print
► PHP echo and print Statements <!DOCTYPE html >
► echo and print are more or less the
<html><head>
<title> today.php </title> </head>
same. <body> <p>
<?php
► They are both used to output data print "<b>Welcome to my home page <br /> <br />";
to the screen.
print "Today is:</b>date("Y/m/d"); print "<br />";
► echo has no return value while ?>
print has a return value of 1 so it
</p>
</body>
can be used in expressions. </html>
► echo can take multiple parameters o/p
(although such usage is rare) while Welcome to my Home Page
Today is 2014/09/24
print can take one argument.
► echo is marginally faster than print. l-day of the week, F-month, j-date value and S –suffix for the day
date(l,F,jS)=>Saturday June 1st
Page 41
Module 2 (CO3, Cognitive Knowledge Level: Apply)
Page 42
Flow Control functions and control statements
Page 43
Flow Control statements in PHP
► Selection Statements
If statement can include any number of elseif clauses.
example of an if construct:
if ($day == "Saturday" || $day == "Sunday")
{$today = "weekend”};
else
{$today = "weekday";}
If($num>0)
$pcount++;
elseif($num<0)
$ncount++;
else
print “Zero”;
Page 44
Flow Control statements in PHP
► Selection Statements
► switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels; }
Page 45
Loop statements in PHP
► The while, for, and do-while statements of PHP are exactly like those of Java.
PHP also has a foreach statement
Example
Page 46
Loop statements in PHP
► For loop
Page 47
Page 48
Loop statements in PHP
► For each loop
Page 49
Basic Programs-Palindrome number
Page 50
Arrays
Page 51
Arrays in PHP
► PHP provides the capability to store data in arrays. Arrays are divided into elements
that behave as individual variables. Array names, begin with the $ symbol.
► Individual array elements are accessed by following the array’s variable name with
an index enclosed in square brackets ([]).
► If a value is assigned to an array element of an array that does not exist, then the
array is created
► assigning a value to an element where the index is omitted appends a new element
to the end of the array
► In PHP, there are three kind of arrays:
> Numeric array - An array with a numeric index
> Associative array - An array where each ID key is associated with a value
> Multidimensional array - An array containing one or more arrays
Page 52
Creating numeric Arrays in PHP
►A numeric array stores each array element with a numeric index.
► > There are two methods to create a numeric array.
1)Assignment operation creates scalar variables. The same operation works for
arrays—assigning a value to an element of an array that does not yet exist creates the
array.
► For example, assuming no array named $list currently exists, the following
statement creates one:$list[0] = 17;
► If the script has a scalar variable named $list prior to this assignment, $ list is now
an array
► If the array currently has no elements with numeric keys, the value 0 is used. For
example, in the following code, the second element's subscript will be 2:
► $list[l] = "Today is my birthday!"; $list[] = 42;
Page 53
Creating numeric Arrays in PHP
►A numeric array stores each array element with a numeric index.
►> There are two methods to create a numeric array.
Page 54
Creating Associative Arrays in PHP
► With an associative array, each ID key is associated with a value.
►When storing data about specific named values, a numerical array is not always the
best way to do it.
► With associative arrays we can use the values as keys and assign values to them.
Page 55
Creating Associative Arrays in PHP
Page 56
Page 57
Functions dealing with Array
1. unset
unset($list[2]);
• Now $list has three remaining elements with keys 0,1, and 3 and
elements 2, 4, and 8.
Page 58
Functions dealing with Array
► The collection of keys and the collection of values of an array can be extracted with built-in
functions.
► The array_keys function takes an array as its parameter and returns an array of the keys of the
given array. The returned array uses 0, 1, and so forth as its keys.
► The array_values function does for values what array_keys does for keys.
Page 59
Functions dealing with Array
• The existence of an element of a specific key can be determined with the array_key_exists function,
which returns a Boolean value. For example, consider the following:
• The is_array function is similar to the is_int function: It takes a variable as its parameter and returns
TRUE if the variable is an array, FALSE otherwise.
• The in_ array function takes two parameters an expression and an array and returns TRUE if the
value of the expression is a value in the array; otherwise, it returns FALSE.
Page 60
Functions dealing with Array
• The existance of an element of a specific key can be determined with the array_key_exists function,
which returns a Boolean value. For example, consider the following:
• The is_array function is similar to the is_int function: It takes a variable as its parameter and returns
TRUE if the variable is an array, FALSE otherwise.
• The in_ array function takes two parameters an expression and an array and returns TRUE if the
value of the expression is a value in the array; otherwise, it returns FALSE.
Page 61
Functions dealing with Array
► sizeof()
• The number of elements in an array can be determined with the sizeof function.
Page 62
Functions dealing with Array-explode and implode
► The explode function explodes a string into substrings and returns them in an array.
► The delimiters of the substrings are defined by the first parameter to explode, which is a string; the
second parameter is the string to be converted.
For example, consider the following:
$str = “May god bless you all";
$words = explode(" ", $str);
$words creates an array which contains (“May", “god", “bless", “you", “all").
► The implode function does the inverse of explode. Given a separator character (or string) and an
array, it concatenates the elements of the array together, using the given separator string between
the elements, and returns the result as a string.
$words = array("Are", "you", “coming", "to“, ”India?”);
$str = implode(" ", $words);
$str has "Are you coming to India?"
Page 63
Functions dealing with Array
► The array_push and array_pop functions provide a simple way to implement a stack
in an array.
► The array_push function takes as its first parameter an array. After this first
parameter, there can be any number of additional parameters. The values of all
subsequent parameters are placed at the end of the array.
► The array_push function returns the new number of elements in the array.
Page 64
Functions dealing with Array
► array_pop function takes a single parameter, the name of an array. It removes the
last element from the array and returns it. The value NULL is returned if the array
is empty.
► array_shift()—This function removes (and returns) the first element of an existing array,
Page 65
To process Array use foreach statement
► The foreach statement is designed to build loops that process all of the elements of
an array.
► This statement has two forms:
foreach (array as scalar_variable) loop body
foreach (array as key => value) loop body
► In the first form, one of the array's values is set to the scalar variable for each
iteration of the loop body.
Ex: $list=array(2,4,6,8);
foreach (Slist as $temp)
print("$temp <br />");
► This code will produce the values of all of the elements of $list
Page 66
To process Array use foreach statement
► The second form of foreach provides both the key and the value of each element of
the array.
Syntax:
foreach (array as key => value) loop body
► For example:
$lows = array("Mon" => 23, "Tue" => 18, "Wed" => 27);
foreach ($lows as $day => $temp)
print("The low temperature on $day was $temp <br />");
Page 67
Sorting Arrays
► sort() - sort arrays in ascending order
► rsort() - sort arrays in descending order
<?php
$fruits = array("Orange", "Grapes", "Apple","Banana");
sort($fruits);
foreach($fruits as $x )
{
echo $x;
echo "<br>";
}
?PPage
>
age 68 Prof.Smitha Jacob, Department of Computer Science and Engineering, SJCET Palai
Sorting Arrays
► sort() - sort arrays in ascending order
► rsort() - sort arrays in descending order
Page 69
Sorting Arrays
► asort() - sort associative arrays in ascending order, according to the value
Page 70
Sorting Arrays
► ksort() - sort associative arrays in ascending order, according to the key
► The sort function, which takes an array as a parameter, sorts the values in the array, replacing the
keys with the numeric keys, 0, 1, 2, ....
► The array can have both string and numeric values.
► The string values migrate to the beginning of the array in alphabetical order. The numeric values
follow in ascending order
Page 71
Sorting Arrays
Page 72
Arrays-Using array_search()
► With the help of array_search() function, we can remove specific elements from an
array.
Page 73
Arrays-Using array_diff()
► With the help of array_diff() function, we also can remove specific elements from an
array.
Page 74
PHP Program to find if an array is a subset of another:
► You need to find whether an array is subset of another array.
► Let us suppose that there are two arrays.First array is large which have 6 values.
► Second array is small which have 2 values.Find if second array is subset of first
which means that all values of second array should exists in first array.
Page 75
PHP Program to check whether an array is empty or not
► An empty array can sometimes cause software crash or unexpected outputs. To
avoid this, it is better to check whether an array is empty or not beforehand. There
are various methods and functions available in PHP to check whether the defined
or given array is an empty or not.
Page 76
MultiDimensional Arrays
Page 77
MultiDimensional Arrays
Page 78
Working with Functions
Page 79
Functions
► Besides the built-in PHP functions, it is possible to create your own functions.
► A function is a block of statements that can be used repeatedly in a program.
► A function will not execute automatically when a page loads.
► A function will be executed by a call to the function.
► A user-defined function declaration starts with the word function
► A function name must start with a letter or an underscore.
► Function names are NOT case-sensitive.They are case-insensitive for the ASCII
characters A to Z
► All functions and classes in PHP have the global scope - they can be called
outside a function even if they were defined inside and vice versa.
► PHP does not support function overloading, nor is it possible to undefine or
redefine previously-declared functions.
Page 80
Functions
Page 81
Functions
► PHP supports user-defined functions
► The general form of a PHP function definition is as follows:
function name( [parameters] ) { }
► Function names are not case sensitive. So, you cannot have a function named sum
and another named Sum.
► the parameters in the call to a function actual parameters.
► the parameters that are listed in the function definition formal parameters.
► The number of actual parameters in a call to a function does not need to match the
number of formal parameters defined in that function.
► If there are too few actual parameters in a call, the corresponding formal
parameters will be unbound variables.
► If there are too many actual parameters, the excess parameters will be ignored
Page 82
Functions-scope of variables
► The default scope of a variable defined in a function is local.
► If a variable defined in a function has the same name as a variable used outside the
function, there is no interference between the two.
► A local variable is visible only in the function in which it is used
► PHP has the global declaration. When a variable is listed in a global declaration in a
function, that variable is expected to be defined outside the function. So, such a
variable has the same meaning inside the function as outside.
► The default lifetime of local variables in a PHP function is from the time the variable
is first used (that is, when storage for it is allocated) until the function's execution
terminates.
► The lifetime of a static variable in a function begins when the variable is first used in
the first execution of the function. Its lifetime ends when the script execution ends
Page 83
Functions
Page 84
Functions-Loosely Typed Language
► PHP is a Loosely Typed Language
► PHP automatically associates a data type to the variable, depending on its value.
Since the data types are not set in a strict sense, you can do things like adding a
string to an integer without causing an error.
In PHP 7, type declarations were added. This gives us an option to specify the
expected data type when declaring a function, and by adding the strict declaration, it
will throw a "Fatal Error" if the data type mismatches.
Page 85
Functions-Loosely Typed Language
► To specify strict we need to set declare(strict_types=1);. This must be on the very
first line of the PHP file.
► In the following example we try to send both a number and a string to the function,
but here we have added the strict declaration:
► it will throw a "Fatal Error" if the data type mismatches.
Page 86
Functions-returning values
Page 87
Functions-PHP Return Type Declarations
► PHP 7 also supports Type Declarations for the return statement. Like with the type
declaration for function arguments, by enabling the strict requirement, it will throw
a "Fatal Error" on a type mismatch.
► To declare a type for the function return, add a colon ( : ) and the type right before
the opening curly ( { )bracket when declaring the function.
Page 88
Functions-Pass by value
► Default parameter-passing mechanism of PHP is pass by value.
► the values of actual parameters are copied into the memory locations associated
with the corresponding formal parameters in the called function.
► The values of the formal parameters are never copied back to the caller, so passing
by value a one-way communication to the function.
Page 89
Functions-Pass by reference
► Pass-by-reference parameters can be done
in PHP in two ways.
► One way is to add an ampersand (&) to
the beginning of the name of the formal
parameter that you want to be passed by
reference.
► The other way is to add an ampersand to
the actual parameter in the function call.
► In PHP, arguments are usually passed by
value, which means that a copy of the
value is used in the function and the
variable that was passed into the function
cannot be changed.
Page 90
Objects
Page 91
Objects
► An object is a sort of theoretical box of things—variables, functions, and so
forth—that exists in a templated structure called a class
► Think of an object as a little box with inputs and outputs on either side of it.
The input mechanisms are methods, and methods have properties.
► an object exists as a data structure, and a definition of that structure called a
class. In each class, you define a set of characteristics.
► For example, suppose you have created an automobile class. In the automobile
class, you might have color, make, and model characteristics
► Each automobile object uses all the characteristics, but each object initializes
the characteristics to different values, such as blue, Jeep, and Renegade, or red,
Porsche, and Boxster.
Page 92
Objects
Page 93
Properties of Objects
Page 94
Properties of Objects
Page 95
Object Methods
Page 96
Object Methods
► The special variable $this is used
to refer to the currently
instantiated object
Page 98
Constructors
Page 100
100
Method 0verriding
Page 101
101
String Comparisons
Page 102
102
String Comparisons
Page 103
103
String Comparisons
Page 104
104
String Processing with Regular Expression
Page 105
105
String Processing with Regular Expressions
► PHP can process text easily and efficiently, enabling straightforward searching,
substitution, extraction and concatenation of strings.
► Text manipulation is usually done with regular expressions—a series of characters that
serve as pattern-matching templates (or search criteria) in strings, text files and
databases.
► A regular expression is a sequence of characters that forms a search pattern. When you
search for data in a text, you can use this search pattern to describe what you are
searching for.
► A pattern is a sequence of characters to be searched for in a character string.
► In PHP, patterns are normally enclosed in slash characters.
/def/ → This represents the pattern def.
► If the pattern is found, a match occurs. For example, if you search the string redefine for
the pattern /def/, the pattern matches the third, fourth, and fifth characters
Page 106
106
String Processing with Regular Expressions
► PHP includes two different kinds of string pattern matching using regular
expressions:
► one that is based on POSIX regular expressions and one that is based on Perl regular
expressions
► Function preg_match uses regular expressions to search a string for a specified
pattern using Perl-compatible regular expressions (PCRE).
► POSIX regular expressions are compiled into PHP
preg_match(regex, str) - Returns a Boolean value
► Perl-Compatible Regular Expression (PCRE) library must be compiled before Perl
regular expressions can be used
preg_split(regex, str) - Returns an array of the substrings
Page 107
107
String Processing with Regular Expressions
Page 108
108
String Processing with Regular Expressions
► preg_match function
► The preg_match() function takes two parameters, the first of which is the Perl-style
regular expression as a string. The second parameter is the string to be searched.
Page 109
109
String Processing with Regular Expressions
► The preg_split function operates on strings but returns an array and uses patterns
► preg_split takes two parameters, the first of which is a Perl-style pattern as a string.
The second parameter is the string to be split.
► For example, consider the following sample code:
$fruit_string = "apple : orange : banana";
$fruits = preg_split("/ : /", $fruit_string);
► The array $ fruits now has ( "apple", "orange", "banana").
Page 110
110
String Processing with Regular Expressions
Page 111
111
String Processing with Regular Expressions
Page 112
112
String Processing with Regular Expressions-Modifiers
Page 113
113
String Processing with Regular Expressions-Modifiers
Page 114
114
String Processing with Regular Expressions
Page 115
115
String Processing with Regular Expressions
Page 116
116
Thank You
Page 117
117