PHP Scripting Language - srimad andavan arts and science college

trampknowledgeSoftware and s/w Development

Nov 4, 2013 (3 years and 9 months ago)

110 views







STUDY MATERIAL

PHP SCRIPTING LANGUAGE

III BCA

AS PER BHARATHIDASAN UNIVERSITY
SYLLABUS (
2011

onwards)

Prepared by T.Vidya

Department

of Computer
Science

Srimad Andavan Arts and Science College



UNIT I

Essential to PHP

1.what is PHP?



PHP is a powerful tool for making dynamic and interactive Web pages.



PHP stands for
P
HP:
H
ypertext
P
reprocessor



PHP is a server
-
side scripting language, like ASP



PHP scripts are executed on the server



PHP supports many databases (MySQl,ORACLE)



PHP is an open source software.


2.How PHP works for the web?



Understanding how the world wide web works is
necessary to understand how PHP
works for web.


2.1 How World wide web works

The Web is a network of computers that offer Web pages. Millions of Web sites are on
the Web. To enable Web surfers to find the Web sites they want to visit, each Web page has an
address, called a
URL.
This includes the Web site’s domain name and the filename, such as
www.mycompany. com/welcome.html. When Web surfers want to visit a Web page, they type
the URL into their Web browsers. The following process is set in motion:

1. The
Web browser sends a message out onto the Web, requesting the Web page.

2. The message is sent to the computer at the address specified in the URL.

3. The Web server software on the addressed computer receives the message.

4. The Web server searches for the

requested HTML file.

5. The Web server finds the requested file and sends the file to the Web browser that requested it.
(If it can’t find the file, it sends a message to the browser saying that it couldn’t find the file.)

6. The Web browser displays the
Web page based on the HTML code it received.


2.2 How PHP works?

PHP software works in conjunction with the Web server. PHP is an
embedded scripting
language that is

PHP code is embedded in HTML code. HTML tags are used to enclose the PHP
language that is

embedded in the HTML file. When PHP is installed, the Web server is
configured to look for PHP code embedded in files with specified extensions like .php or .phtml.
When the Web server gets a request for a file with the designated extension, it sends the
HTML
statements as is, but PHP statements are processed by the PHP software before they’re sent to the
requester. When PHP language statements are processed, the output consists of HTML
statements. The PHP language statements are not included in the HTML s
ent to the browser.







3. Steps for saving and executing PHP scripts




PHP scripts are embedded within the <?php and ?> tags.



The file containing PHP code must be saved with .php extension



A PHP enabled web server needs to be installed.



The PHP file must

be placed in a directory that the web server looks for when servicing a
request. This directory can vary from server to server. For example, if WAMP server is
installed, the PHP and HTML files must be placed in the www directory of the server
installation

directory.



The URL to the PHP file must be specified in the address bar of the web browser. If the
server and browser are on the same machine and the name of the PHP file is test.php
which is placed in www directory, then the URL will be
http://localhost/test.php
.



The request from the browser gets dispatched to the server and the server executes the
PHP code and the HTML output is sent to the web browser. The browser interprets the
HTML tags and the output is present
ed in the appropriate manner.


4. PHP syntax




PHP code must be embedded between the starting <?php tag and the ending ?> tag.



A PHP statement is one that tells PHP to perform some action. Every statement in PHP
must end with a semicolon.



PHP ignores white
spaces(space, newline and tab) within statements.



Several statements are combined into a block, which is enclosed by curly braces ({}).
Statements in a block execute together. Statements that use a block are called complex
statements.


5.COMMENTS IN php


C
omments are human readable annotations that we add to make our code readable.It
describes what the script does and how it does.There are two types of comments available in php
they are:

i)Single line comments:We use // to represent single line comments.

i
i)Multiline comments:This comment starts with /* and end with */.

Example:

1)<?php


echo "hello";


//this is a comment


echo " there";


?>



2)<?php


echo "hello";


/*


Using this method


you can create a larger block of text


and it will all be commented out


*/


echo " there";


?>



6.ECHO :


Echo statement is an output statement that is used for displaying output. The general
form of echo statement is


echo
outputitem1
,
outputitem2
,
outputitem3
, . . .




An
outputitem
is a
number or a string of characters. Numbers are things like 1 or 250. A
string is a string of characters, which can include numbers.



Enclose a string of characters with single or double quotes.



List as many
outputitem
s as needed.




Separate each
outputitem
w
ith a comma.


Examples of echo statements with output


Echo statement

Output

echo 123;

123

echo “Hello World!”;

Hello World!

echo “Hello”,”World!”;

HelloWorld!

echo “Hello”,” “,”World!”;

Hello World!

echo Hello World!;


Not valid because the string

is not enclosed

in quotes; results in an error message

echo ‘Hello World!’;

Hello World!


6.1 Special characters in output statement.



Special characters such as
\
n,
\
t can be included in the output statement.
\
n is for a
newline and
\
t for tab. These

special characters are only for PHP output. The browser ignores
these and displays only a space. To introduce a newline in the browser <br> tag must be used.

Example:


<?php


echo "hello";


//this is a comment


echo " there";


?>



OUTPUT: hello ther
e


7.Variables:



Variables are used for storing values, like text strings, numbers or arrays.



When a variable is declared, it can be used over and over again in your script.



All variables in PHP start with a $ sign symbol.



A variable should start with a let
ter or by the symbol(_)underscore.


Creation of a Variable:

The correct way of declaring a variable in PHP:

$var_name = value;


*Datatype is not specified during declaration.According to the assigned value the variable will
act as an integer,float or
string.

Example:


<?php

$txt="Hello World!"; //Here the variable txt is of string datatype.

$x=16;




//Here the variable x is of type integer.

$x1=16.2345;


//Here the variable x1 is of float datatype.

?>

The following simple data types are supported
by PHP

Integer:
A whole number (no fractions), such as

43, 0, 1, 27, or 5438. The range of integers that
is allowed varies, depending on the operating system

Floating point number:
A number (usually not a whole number) that includes decimal places,
such as 5.24 or 23.456789. This is often called a
real number
or a
float.

Character string:
A series of single characters, such as hello. There is no practical limit on the
length of a str
ing.

Boolean:
A TRUE or FALSE value. The string FALSE (can be upper
-

or lowercase), the integer
0, the float 0.0, an empty string and the constant NULL are considered FALSE. When Boolean
values are displayed FALSE displays as a blank string and TRUE echoe
s a 1.


7.1 Conversion of Data Types of variables


If there are two variables of different data types in an expression, PHP automatically
converts and promotes the data type of one variable to the data type of the other variable with
higher precision.

Exam
ple:

$firstNumber = 1; // PHP stores it as an integer

$secondNumber = 1.1; // PHP stores it as a float

$sum = $firstNumber + $secondNumber;


In the above piece of code, the data type of $firstnumber is automatically converted to
float by PHP.


If a number
is enclosed within a string, in arithmetic expressions, the string containing
numbers is automatically converted to a number.

Example:

$var1 = “1”;

$var2 = 2;

$total = $var1 + $var2;

Here, the value in $total is 3 because PHP automatically converts “1” to
1.

If a String is used in an arithmetic expression and it does not contain any number, then
PHP treats the string as number 0 in evaluating the expression.

The programmer also can change the way a variable is stored by using specific type cast.
The value i
n the variable on the right side of the equal sign is stored in the variable on the left
side as the specified type.

Example:

$intvar = 10;

$floatvar = 100.10;

$intvar = (int)$floatvar;


In the above example, the value in $floatvar is converted to integer
and stored in $intvar.
After the type cast, $intvar contains the value 100.



7.2Displaying the variable:




The value in a variable can be displayed using the echo statement.



The data type of a variable can be displayed using the var_dump function. To
display the
data type of a variable $var we can use var_dump($var).


7.3 Removing Variables


The information in a variable can be removed setting the variable to an empty string. For
example setting $var = “” removes the information stored in the variable.

If the variable $var is
displayed, nothing in echoed.



A variable can also be uncreated using the unset function. Passing a variable or variables
as parameter to the unset function uncreates the variable. Any further use of the variable will
give an unde
fined variable error.


8.Constants


Constants are similar to variables, that is they act as a placeholder for storing values. But
the value stored in a constant cannot change during the execution of the script.


8.1 Constant creation


Constants are created

using the define statement. The format for creating a constant is
define(“
constantname
”,”
constantvalue
”);


8.2 Points to remember when using constants



The name of a constant does not begin with a $



We can store either a string or a number in a constant



By

convention constant names are given in Capital letters but PHP accepts lowercase
letters also.



When using a constant in an expression, the double quotes must be removed.



Using a constant ensures that the value won’t be changed accidentally somewhere in th
e
script, leading to the wrong value being used in statements later in the script


Example




define(“INTEREST”, 10.2);


The following statement defines a constant named INTEREST and assigns to it the value
10.2. This constant can be used as $a=INTEREST
*$b;

STRINGS:

9
.Strings


A
character string
is a series of characters and c
haracters
are letters, numbers, and
punctuation.


Character strings are stored in a variable by using double quotes(“) or single quotes (‘)
which mark the beginning and end of the
string.


Special characters like
\
n (for newline)
\
t(for tab) can be used only within strings created
using double quotes. In single quoted strings special characters have no meaning and they are
output as any other character.


The difference between using

single quotes and double quotes are as follows



Single
-
quoted strings are stored literally, with the exception of
\
’, which is stored as an
apostrophe.
\
n and
\
t are echoed literally. A variable $var inside a single quoted string is
displayed as $var itsel
f and not by its value.



In double
-
quoted strings, variables and special characters are evaluated before the string
is stored. For example
\
n is treated as a newline and display moves to the next line when
echo is used $var inside a double quoted string is
evaluated for its value.


9.1 Escaping characters within strings


Characters that tell PHP to remove the special meaning of certain characters in a string
and treat them as literals are called escaping characters. The special meaning of a character can
be
removed by preceding it with a
\
.

Examples:


Preceding $ with
\

removes its special meaning and the characters following $ are not
treated as variables. echo “
\
$var”; will output $var and not the value in $var.


Similarly
\

and “ can also be escaped by usi
ng
\

before them.


9.2 String Concatenation:


The process of joining strings is called as concatenation. Strings can be joined in PHP
using the .(dot) operator.

Example:


$a = “Hello”;


$b = “World”;


$c = $a.$b; // $c = HelloWorld


9.3 Inbuilt functions
for String manipulations


1.

trim($str), ltrim($str) and rtrim($str)

The trim functions are used for removing leading and/or trailing spaces in a string. trim()
removes both leading and trailing spaces, ltrim removes leading spaces and rtrim
removes trailing
spaces.


2.

str_word_count($str)

This functions returns the number of words in the string $str.

This function can also be invoked with one more parameter. If this function is called as
str_word_count($str,1), then the words in the string are returned as an ar
ray with the first
word at index 0.


3.

str_repeat($str,$n)

This function repeats the string $str $n times and returns it as a string


4.

str_replace($a,$b,$str)

This function replaces all occurrences of $a with $b in the string $str and returns the new
string.


5.

strlen($str)

This function returns the length of the string $str.


6.

strpos($str, $substr)

This function returns the position of first $substr beginning in $str.


7.

strrev($str)

This function reverses the string and returns it.


8.

strtolower($str)

This function

returns the lowercase version of the string $str.


9.

strtoupper($str)

This function returns the uppercase version of the string $str.


10.

substr($str,$n1,$n2)

This function returns the substring from position $n1 for upto $n2 chracters in $str and
returns it.


11.

strcmp($str1,$str2) and strcasecmp($str1,$str2)

Compares two strings on alphabetical and numerical order . Returns
-
1 if
str1
is less, 0 if
two strings are equal, or +1 if
str1
is greater. strcmp is casesensitive. strcasecmp is not.



10.Operators



The
following operators are available in PHP

• Assignment Operators

• Arithmetic Operators

• Comparison Operators

• String Operators

• Combination Arithmetic & Assignment Operators




Execution operators



10.1 Assignment Operators:


Assignment operators
are used to set a variable equal to a value or set a variable to
another variable's value. Such an assignment of value is done with the "=", or equal character.

Example: $var = 100;


$str = $another_var;


10.2Arithmetic Operators


Arithmetic operators perf
orm simple arithmetic operations on the operands. The different
arithmetic operators are


Operator

Description

+

Adds two numbers together.

-

Subtracts the second number from the first number.

*

Multiplies two numbers together.

/

Divides the first
number by the second number.

%

Finds the remainder when the first number is divided by the second number.
This is called
modulus.


10.3Comparison Operators


Comparisons are used to check the relationship between variables and/or values.
Comparison operat
ors are used inside conditional statements and evaluate to either
true
or
false
.

Example: Let $x = 4 and $y = 5



Operator

Description

Example

Result

==

Equal to

$x==$y

False

!=

Not equal to

$x!=$y

True

<

Less than

$x<$y

True

>

Greater than

$x>$y

False

<=

Less than equal to

$x<=$y

True

>=

Greater than equal to

$x >=$y

False


10.4String Operator


Period (.) is the string operator. It is used to concatenate/join two strings together.

Example:

$a_string = "Hello";

$another_string = " Billy";

$new_string = $a_string . $another_string;

echo $new_string . "!";


Output

Hello Billy!


10.5Combining multiple comparison operators


Multiple comparison operators can be combined using the keywords and|or|xor using the
format comp1 and|or|xor comp2. The
way these words are used are as follows:

and: For testing whether both comparisons are true.

or: For testing whether one of the comparisons or both of the comparisons are true.

xor: For testing whether one of the comparisons is true but not both of the com
parisons.

Example:

Condition

Is true if

$ageBobby == 21 or $ageBobby == 22

Bobby is 21 or 22 years of age.


$ageSally==29 and $state==”TamilNadu”

Sally’s age is 29 and lives in Tamilnadu

$choice==”Coffee” xor $choice==”Tea”

Choice is either coffee or
tea but not both



10.6Combination Arithmetic and Assignment Operators


These operators combine the arithmetic and assignment operation using a single operator.

Example:

$x+=5 implies $x = $x +5.


These combinations can be used with all the arithmetic op
erators and also the string
operator.


10.7Pre/Post Increment and Pre/Post Decrement Operators


The operators ++ and


are used to add 1 or subtract 1 from a variable. Pre
Increment/Decrement operator is used before the variable and Post Increment/Decremen
t
operator is used after the variable.

When Pre increment/decrement operator is used, the value of the variable gets changed before
being used.

When Post increment/decrement operator is used, the value of the variable gets used first and
later is gets inc
remented/decremented.


Increment/decrement Operators

Example

Name

Effect

++$a

Pre
-
increment

Increments
$a

by one, then returns
$a
.

$a++

Post
-
increment

Returns
$a
, then increments
$a

by one.

--
$a

Pre
-
decrement

Decrements
$a

by one, then returns
$a
.

$a
--

Post
-
decrement

Returns
$a
, then decrements
$a

by one.

Here's a simple example script:

<?php

echo

"<h3>Postincrement</h3>";

$a

=

5;

echo

"Should

be

5:

"

.

$a++

.

"<br

/>
\
n"; //5

echo

"Should

be

6:

"

.

$a

.

"<br

/>
\
n"; //6


echo

"<h3>Preincrement
</h3>";

$a

=

5;

echo

"Should

be

6:

"

.

++$a

.

"<br

/>
\
n"; //6

echo

"Should

be

6:

"

.

$a

.

"<br

/>
\
n"; //6


echo

"<h3>Postdecrement</h3>";/

$a

=

5;

echo

"Should

be

5:

"

.

$a
--

.

"<br

/>
\
n";//5

echo

"Should

be

4:

"

.

$a

.

"<br

/>
\
n";//4


echo

"<h3>Predec
rement</h3>";

$a

=

5;

echo

"Should

be

4:

"

.

--
$a

.

"<br

/>
\
n";//4

echo

"Should

be

4:

"

.

$a

.

"<br

/>
\
n";//4

?>



10.8Execution operator:




The execution operator allow s to execute system commands such as windows date or dir
commands.Execute a system c
ommand is to enclose it in backticks(`).

EX: The following code runs the date command.

<?php

$output=`date`;

Echo $output;

?>

The output gives the current date for eg. As 24/6/1995


10.9OPERATOR PRECEDENCE:




Operator precedence says the order in which op
erators gets executed.




The following table lists the operators in order of precedence, with the highest
-
precedence ones at the top. Operators on the same line have equal precedence.

OPERATOR PRECEDENCE

( )(highest precedence)


* /%

+
-

Example:

<
?php

Echo “(4+3) * 9=”, (4+3) * 9,”<br>”;

?>

OUTPUT:63



Here the brackets () has the highest precedence so the operations within the bracket is
evaluated first that is(4+3) =7.



Then Multiplication is carried out which evaluates 7*9=63.

11.Arrays

Arrays are
complex variables that store a group of values under a single variable name.
An array is useful for storing a group of related values.

In PHP arrays are nothing but group of key/value associations under a single array name.
The keys can be either numeric o
r text. Depending on the type of key, the arrays are classified as



Numeric Arrays (Keys are numbers)



Associative Arrays (Keys are strings)


11.1 Creation of Arrays


Arrays can be created in the following ways


11.1.1.By specifying the key/value
association for every element:

Example for creating numeric array:

$studname[1] = “Anil”;

$studname[2] = “Bheema”;


This creates an array called $studname with two elements and they can be accessed as
$studname[1] and $studname[2]. The key/value associatio
ns are 1/Anil and 2/Bheema.


Example for creating Associative array:

$state[‘TN’] = “Tamil Nadu”;

$state[‘KA’] = “Karnataka”;

$state[‘AP’] = “Andhra Pradesh”;


This creates an associative array with 3 elements.


11.1.2By not giving any key for the array


A
n array can be created by not giving any specific key to the values. This automatically
creates an array that starts at key number 0.

Example:

$streets[] = “MG St.”;

$streets[] = “Renga St.”;

$streets[] = “Andar St.”;


This creates an array called $street
with 3 elements and the first element can be located at
$streets[0].


11.1.3By using the array function

Example for creating numeric array:

$vowels = array(‘a’,’e’,’i’,’o’,’u’);


This creates an array with 5 elements and the first element starts at index
0.

Example for creating associative array

$counCap = array("India" => "NewDelhi","China"=>"beijing");


This creates an associative array with 2 elements. The following key/value associations
are made

$counCap[“India”] = “NewDelhi”;

$counCap[“China”] = “Bei
jing”;

11.1.4By specifying a range

An array with a range of values can be created by using the following statement:

$years = range(2001, 2010);

The resulting array looks like the following:

$years[0] = 2001

$years[1] = 2002

. . .

$years[8] = 2009

$years[9]

= 2010


11.2 Appending an existing array


An existing array can be appended by not specifying the key for the new value to be
added. PHP automatically gives the next number as the key for both numeric and associative
arrays.

Example:

In the above $counCap

array, the following entry can be made

$counCap[] = “Colombo”;


Here, “Colombo” gets added to the array and is automatically associated with the key 0.

Similarly, in the above $years array, the statement $years[] = 2011; associates 2011 to key 10.


11.3Vi
ewing Arrays

The structure and values of any array can be viewed by using one of two statements


var_dump or print_r.

Example:

$customers= array(“Ram”,”Laksman”,”Sita”);

print_r($customers) will give the following output


(

[1] => Ram

[2] => Lakshman

[3]
=> Sita

)

Var_dump($customers) gives the following output

array(3) {

[1]=>

string(9) “Ram”

[2]=>

string(9) “Laksman”

[3]=>

string(10) “Sita”

}

11.4Removing values from Arrays


A value can be removed from an array using the unset($arrname[key]) statement. A
n
array also can be completely removed using the unset($arrname) statement.


Using Arrays in echo


To display an array element $arrname[2], it can be used in echo as echo $arrname[2];


To display an array element value in an echo statement containing
double quotes, then
the array element reference must be enclosed within curly braces as follows:


echo “The value of array element 2 is {$arrname[2]}”;


11.5 Handling arrays with loops:


For loop:


Arrays and loops are natural combination

arrays are index
ed using an array index,and
loops use a loop counter.By using the loop counter as the array index we can increment through
an entire array.


EX:

<?php

$actors[0]=”sathyam”;

$actors[1]=”sivam”;

$actors[2]=”sundaram”;

For($loop_index=0;$loop_index<count($act
ors);$loop_index++)

{

Echo “ $actors($loop_index)=”,$actors($loop_index),”<bre>”;

}



Here the count($actors) gives the no. of values stored in the array actor.i.e.,3.



From index 0 to 2 the values are extracted from the array .the output of the pgm is

$acto
rs[0]=sathyam

$actors[1]=sivam

$actors[2]=sundaram


FOREACH loop:



It is used to work with arrays.Here there is no initialization or termination conditions.

EX:

<?php

$actors[0]=”sathyam”;

$actors[1]=”sivam”;

$actors[2]=”sundaram”;

Foreach($actors as
$value)

{echo “value:,$value,<br>”;

}

?>


Output:

Value=sathyam

Value=sivam

Value=sundaram


WHILE loop:




While loop is used to iterate over an array by using
each

function.



The each function returns the current element’s key and value.

Ex:

<?php

$debts[“trichy”]=”cauvery”;

$debts[“madurai”]=”vaigai”;

While(list($key,$value)=each($debts))

{

Echo “key: $key;value: $value<br>”;

}

?>

Output:

Key:trichy;value=Cauvery

Key:Madurai;value=vaigai

11.6Array Functions


11.6.1 Sorting Functions:


Sorting funct
ions are used to sort the elements of the array. The different sorting
functions are:

1.

sort($arrname):



Sort function sorts arrays by the values and assigns new keys that are the appropriate
numbers. The values are sorted with numbers first, uppercase lette
rs next, and lowercase
letters last.



If sor’t() is used to sort an array with words as keys, the keys are changed to numbers,
and the word keys are thrown away.

Example: If sort() is used on the following array,

$streets[0] = “Elm St.”;

$streets[1] =
“Oak Dr.”;

$streets[2] = “7th Ave.”;

The output after sorting is

$streets[0] = “7th Ave.”;

$streets[1] = “Elm St.”;

$streets[2] = “Oak Dr.”;


2.

asort($arrname):



This function is used to sort arrays that have words for keys.



This function sorts the array elem
ents by value, but it keeps the original key for each
value instead of assigning a number key.

Example: If asort() is used in the following array,

$capitals[‘CA’] = “Sacramento”;

$capitals[‘TX’] = “Austin”;

$capitals[‘OR’] = “Salem”

The output after using
asort() is

$capitals[‘TX’] = Austin

$capitals[‘CA’] = Sacramento

$capitals[‘OR’] = Salem


3.

rsort($arrname):


Sorts by value in reverse order; assigns new numbers as the keys.


4.

arsort($arrayname):

Sorts by value in reverse order; keeps the same key.


5.

ksort($arrayname):

Sorts by key.


6. Functions for traversing an array manually


Arrays can be traversed manually using pointers. A pointer points to a particular value in
the array. It stays there until it is moved. Unless a pointer has been moved previou
sly, it points to
the first value in the array. The different functions to move the pointers are as follows:




current($arrayname): Refers to the value currently under the pointer. Does not move the
pointer



next($arrayname): Moves the pointer to the value a
fter the current value



previous($arrayname): Moves the pointer to the value before the current pointer location



end($arrayname): Moves the pointer to the last value in the array



reset($arrayname): Moves the pointer to the first value in the array

Example:

$capitals=array(“TN”=>”Chennai”,”Karnataka”=>”Bangalore”,”AP”=>”Hyderabad”);

$val = current($capitals); //$val = Chennai

$val = next($capitals); //$val = Bangalore

$val = end($capitals); //$val = Hyderabad

reset($capitals);

$val = current($capitals); //$va
l = Chennai


7. count($arrname) and sizeof($arrname):


These two functions are used to find the size or the number of elements in the array.
These function return the size of the array $arrname.


8. Functions for converting strings to arrays and vice versa

explode($sep_char,$str)


This function creates an array of substrings from the string $str. $sep_char is the
character/string that is used to divide the $str into substrings. A numeric array starting at index 0
is created.

Example:

$string1 = “This:is a:
new:house”;

$testarray = explode(“:”,$string1);

print_r($testarray);

The ouput is

Array

(

[0] => This

[1] => is a

[2] => new

[3] => house

)

The explode statement tells PHP to split the string at each colon (:) and create an array
containing the substrings.


9.implode($sep_char,$arr)


This is the converse of explode(). This takes an array and a separating character as
parameter and converts the elements of the array into a string by separating each element of the
array in the string by the separating charact
er.

Example:

$arrayIn = array( “red”, “blue”, “green”);

$stringOut = implode(“;”,$arrayIn);

echo $stringOut;

The output is

red;blue;green


10. Functions for converting Arrays to variables and vice versa

extract($arrname)


Extract function is used retrieve
all the values from an array, and insert each value into a
variable, by using the key for the variable name. In other words, each array value is copied into a
variable named for the key.

Example:

$testarray = array( “pink”=>”Lotus”, “red”=>”rose”);

extract
($testarray);

echo “My favorite red flower is a $red.
\
n”;

echo “My favorite pink flower is a $pink.”;

The output is:

My favorite red flower is a rose.

My favorite pink flower is a Lotus.


compact($var1,$var2…)


This function creates an array from the
specified variables ($var1, $var2, and so on). The
variables can be strings or arrays. It copies the value from each specified variable name into an
array element. The variable names are used as keys. The variables can be specified in two ways

1.

Variable nam
es can be used directly as strings

2.

An array that contains the names of the variables can be used.

Example:

$color1 = “red”;

$color2 = “blue”;

$a = “purple”;

$b = “orange”;

$arrayIn = array(“a”,”b”);

$arrayOut = compact(“color1”,”color2”,$arrayIn);

The arra
y arrayOut is given below after the compact statement

$arrayOut[color1] = red

$arrayOut[color2] = blue

$arrayOut[a] = purple

$arrayOut[b] = orange


11. Functions for splitting and merging arrays


array_slice($arrname, $n1, $n2)


This function creates a new

array that contains a subset of an existing array. $arrname is
the existing array. $n1 is the is the sequence number of the element where the new array should
start. $n2 is the length of the new array. Even for associative arrays, $n1 must be the sequence

number and not the key.

Example:

$testarray = array( “red”, “green”, “blue”,”pink”);

$subArray = array_slice($testarray,1,2);

The array $subarray is

[0] => green

[1] => blue


array_merge($arr1, $arr2,..)


This function merges the arrays specified by
$arr1, $arr2 and so on into a single array.


If the keys are words and are the same for any of the elements, the later element with the
same key word will overwrite the first element of the same key.

Example 1: Arrays with numbers as keys

$array1 = array(“
red”,”blue”);

$array2 = array(“green”,”yellow”);

$bigArray = array_merge($array1,$array2);

After the statement, $bigArray is the following array:

$bigArray[0] = red

$bigArray[1] = blue

$bigArray[2] = green

$bigArray[3] = yellow

Example 2: Arrays with words

as keys and having the same key

$array1 = array(“color1”=>”red”,”color2”=>”blue”);

$array2 = array(“color1”=>”green”,”color3”=>”yellow”);

$bigArray = array_merge($array1,$array2);

The output array is as follows:

$bigArray[color1] = green

$bigArray[color2]

= blue

$bigArray[color3] = yellow


12. Comparing Arrays


array_diff($arr1, $arr2,…..)


This function returns an array that contains the elements(values) from $arr1 that are not
present in any of the other listed arrays. The elements in the result array
will have the same keys.

Example:

$array1 = array( “a”=>”apple”, “b”=>”orange”, “c”=>”banana”);

$array2 = array( “prune”, “orange”, “banana” );

$diffArray = array_diff($array1,$array2);

After this code, $diffArray looks like this:

$diffArray[a] = apple;


a
rray_diff_assoc($arr1, $arr2, ….)


This function returns an array that differ in either the value or the key with $arr1 and the
other arrays.

Example:

If $array1 and $array2 are as in the previous example, then

$diffArray = array_diff_assoc($array1,$array2
);

will give the following output

$diffArray[a] = apple

$diffArray[b] = orange

$diffArray[c] = banana


array_intersect($arr1, $arr2,….)


This function creates an array that contains the elements(values) that are the same, rather
than different, in two or m
ore arrays.

Example:

$array1 = array( “a”=>”apple”, “b”=>”orange”, “c”=>”banana”);

$array2 = array( “prune”, “orange”, “banana” );

$simArray = array_intersect($array1,$array2);

The results array would look like this:

$simArray[b] = orange

$simArray[c] =
banana


array_intersect_assoc($arr1,$arr2,….)


This functions creates an array whose keys and elements are common among all the
arrays given as parameters to the function.

Example:

Using the above two same arrays,

$simArray = array_intersect_assoc($array1,
$array2);

The output array $simArray is empty because none of the keys and values are same.


13. array_sum($arr)


This function adds all the values in an array.

Example:

$arrayAdd = array(3,3,3);

$sum = array_sum($arrayAdd);

echo $sum;

The ouput is 9.


7.5
.10.array_unique($arr)


This function creates an array by removing the duplicate elements of $arr. The resulting
array has elements that have no duplicates.

Example:

$names = array( “Mary”, “Sally”, “Sally”,”Sam”);

$names2 = array_unique($names);

The array

$names2 looks like this:

$names2[0] => Mary

$names2[1] => Sally

$names2[3] => Sam


14. array_flip($arr)


This function creates an array with the values and keys exchanged from the original array
$arr.

Example:


$testarray[‘rose’] = red

$testarray[‘iris’]
= purple

$arrayFlipped = array_flip($testarray);

The array $arrayFlipped looks like this:

$testarray[‘red’] = rose

$testarray[‘purple’] = iris


11.7 Multidimensional Arrays


These are arrays whose elements themselves are arrays.


Creating a multi dimension
al array Example:

$Marks[‘ramu’][‘english’]=80;

$Marks[‘ramu’][‘maths’]=90;

$Marks[‘shamu’][‘english’]=76;

$transportation[‘car’][] = “Ford”;

$transportation[‘car’][] = “Jeep”;


In the above example, when the key for the second dimension is omitted, numeri
c keys
are automatically assigned.


Therefore, “Ford” can be accessed as $transportation[‘car’][0].



Multidimensional arrays can also be created using array statement.

Example:

$foodPrices = array(

“vegetable”=>array(“potato”=>1.00,”onion”=>.50),

“fruit”=>array(“apple”=>2.50,”orange”=>2.00));


7.6.1 Using multi dimensional arrays in statements:


When the keys for both the dimensions are specified, a single element of the multi
dimensional array can be accessed.


When the higher dimension key alone
is specified, it accesses the corresponding element
which is an entire array. Hence a multi dimension array with only the higher key can be used in
array functions which expect a single array as parameter.


7.6.2. Traversing a multidimensional array


A mut
i dimensional array can be traversed using two foreach constructs. A multi
dimensional array can be viewed as an array of arrays. The outer foreach construct is used to
retrieve every row of the 2D array and the inner foreach construct to visit every eleme
nt in the
retrieved array.


Example:

$multi['a']['a'] = 10;

$multi['a']['b'] = 20;

$multi['b']['a']=100;

$multi['b']['b']=200;


foreach($multi as $rkey => $row)

{


echo $rkey."<br>";


foreach($row as $key => $val)



echo "$key:$val ,";


echo "<br>";

}

The
output is:

a

a:10,b:20,

b

a:100 ,b:200 ,




UNIT II

Functions:



Callable code to which data can be passed and returned



Breaks up code so that the same piece of code can be executed from different points
without redundancy



Easy to comprehend



Creating and Cal
ling functions



Function definition syntax


function
function_name
($arg1, $arg2,…..)


{



statements;



return
return_value


}


function and return are keywords


function_name is the user given name to the function


$arg1, $arg2…… are the parameters passed

to the function. The arguments can be both
variables and arrays


return_value is the value returned from the function

Function is called by giving the name of function and giving the arguments within parentheses. If
the function returns a value, it is ass
igned to a variable

Example of function definition:

<?php




$num = $_POST['num'];




if($num=="")





echo "Enter a number";




else




if($num < 0)





echo "Enter a positive number";




else




{





echo "Factorial of $num = ".factorial($num);









}




function factorial($n)




{





if($n == 0)






return 1;





else





{






$fact = 1;






for($i=1;$i<=$n;$i++)







$fact*=$i;






return $fact;





}




}



?>


Pass by Value and Reference



Parameters are passed to function by value by
default. Pass by value means, a copy of the
actual argument is sent to the function through a different memory location. Hence the
changes made to the parameter in the function are not visible to the calling function.



If we want the changes made to the par
ameter in the function to be visible to the calling
function, then the parameter must be passed by reference.
In pass by reference, the
address of the variable is passed to the function.Hence, the operations performed on the
variable inside the function wi
ll be reflected on the variable that was passed outside the
function since they have the same memory address.

Example for pass by reference:


function square(&$n)


{



$n *= $n;


}



$a = 5;


square($a);


echo $a;


The function square is defined for accept
ing parameters passed by reference. In the above
example, the variable $a is passed by reference and hence after squaring the variable, the squared
value will be displayed by the echo statement. The output in this case will be 25.

Example Pass by value:

Ex
ample for pass by reference:


function square($n)


{



$n *= $n;


}



$a = 5;


square($a);


echo $a;


Here, $a is passed by value and hence after square() is invoked, the changes are not
visible outside the function and hence output will be 5 and not 25.

F
unctions with default arguments



If a function takes two parameters and a caller passes only one argument , then PHP will
report an error stating “Missing argument”



To avoid this error, we can give a default value to the argument and this default value
will

be used.



But once we start giving default values to arguments, then all args following the first
default value must also be given default values

Example:


function foo($x, $y = 5)


{



return $x + $y;


}



echo foo(10,3), "<br>";


echo foo(6);


In the
above example, the first call to foo passes two arguments and hence the output is
10+3 = 13 but in the second case, only one argument is passed and hence the default argument
value 5 is taken as the value for argument $y and hence the output would be 6 + 5

= 11.


Functions with variable number of arguments



Functions that can accept any number of arguments are called functions with variable
arguments.



The function definition does not specify any arguments



Three inbuilt PHP functions are used to access the
arguments passed


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

Example:


function combine()


{



$args = func_get_args();



$str = "";



foreach($args as $
val)




$str.=$val;




echo $str , "<br>";


}



combine("Hello", "How do u do?", "I am fine");


combine("Good", "Morning");


combine();


The example function combine() defined above can take any number of arguments. This
function concatenates all the
arguments passed to it and echoes the concatenated string. The
inbuilt function func_get_args() returns all the arguments passed to it as an array and the array is
processed to perform the concatenation.


References in PHP

References are nothing but pointe
rs. That is these are variables that hold the address of another
variable. If one variable changes the value, then it will be reflected in the other variable also.

$val = 4;

$ref = & $val;

$ref++;

echo $val

Here the ouput will be 5 since both $ref and $va
l point to the same memory location.


Functions returning references



For a function to return a reference, the function must be defined with ‘&’ prefixed
before the name of the function


function &func_name($arg)


{



return $arg;


}

The calling function
assigns the returned value as follows

$ref = &func_name($param);


Scope of variables



Scope of a variable means the portions of the code where that variable is accessible



Scope can be of three types



local scope



global scope



static scope



Local scope: Variables defined in a function can be accessed only in that function. If a
function defines a variable that is already defined outside the functions, then any use of
the variable inside the function will refer only to the local variable.



Glo
bal scope:



If we want to use a variable in a function that has been defined outside the
function then the variable can be accessed using the global keyword before the name of the
variable. Then any usage of that variable will refer to the global variable
.



Static Scope



In local scope, when a function gets called repeatedly, then all the local variables
will be reinitialized with each call. But if we do not want to get the local variable
reinitialized for every call, then the keyword static is used before t
he variable
name. The variable defined like this will retain its value between function calls.

Example global scope:


function scope()


{



global $a;



echo $a;



$a = 500;


}


$a = 200;


scope();


echo $a;


In the example above, $a is defined outside th
e function scope(). If we want to access $a
which has been defined outside scope(), then the variable must be preceded by the keyword
global to indicate that the variable being used is not a new one and that it is the variable which
has been defined outsid
e the function globally. Hence inside scope(), echo $a will display 200
and after scope() has been called, echo $a outside will display 500 since both $a are the same.

Example local scope:


function scope()


{



$a;



echo $a;



$a = 500;


}


$a = 200;


scope();


echo $a;

Here, the keyword global has been removed. The $a inside scope() will be considered a new
variable and echo $a inside scope will display the value 0 and echo $a after calling scope() will
display 200 because the $a inside scope() and $a
outside scope() are different.


Example for static scope()


function staticscope()


{



static $a = 0;



$a++;



echo "$a ";


}




staticscope();


staticscope();


Here, since $a has been preceded by the keyword static, it will be initialized only once.
Af
ter the first call, any subsequent call will retain the old value. Here, the output will be 2 after
staticscope() is called twice.


Conditional functions



These are functions that are defined inside conditional statements



These functions get defined only wh
en the conditional statement gets executed.



The conditional function can be called normally if the conditional statement enclosing the
function has executed successfully

Example:


$func_created = false;


if(true)


{



function fn()



{




echo “Conditional

function”;



}



$func_created = true;


}


if($func_created)



fn();


Variable functions



Variables can be assigned string values which are names of functions. Then the variable
name can be used to call different functions by assigning different function
names

function red()

{


echo “In red”;

}

function white()

{


echo “In white”;

}

$var = “red”;

$var();

$var = “white”;

$var();


Here, $var is assigned the value “red” first and hence $var() will invoke red() and later
$var is assigned “white” and hence
$var() will invoke white().


Include and Die functions



Include function is used to insert the contents of a file into the code file. Typically
constants, menus and other data that need to be used across many scripts are stored in a
file. This file name is
given as parameter to the include function and the contents will be
inserted

Constant.inc

<?php


define(“PI”,3.14);

?>

Another.php

<?php


include(“constant.inc”);


echo PI;

?>


Die function



Functions can report errors by returning a boolean value. Usual
ly if the boolean value
TRUE is returned, then it is assumed that the called function executed successfully. If it
returns FALSE, then it implies that there was an error in its execution.



The calling function can take appropriate action depending on the va
lue returned



To take necessary action when the execution of the called function fails, die function is
used.



Usage: function_name() or die (“error statement”)


If the function_name() returns true, then the execution will proceed normally.


If the funct
ion_name() return false, then the die function will be executed which will
print the error statement and the execution of the script will be terminated


Reading data from web pages



To send data to a server , the HTML page must be set up using form tag



A
form is a construct in HTML which enables users to interact and enter data that can be
further processed on the server



Form tag has two attributes



method : specifies the way in which data is to be sent to the server (GET or
POST)



action : specifies the

URL where the data is to be sent



If action attribute is not specified, then data is sent to the same URL


Input Controls in a form



A form can have different kinds of input controls associated with it. Each type of input
control is specified by a input
tag.



Input fields are added to forms by using specific tags. The input field tags must come in
between the <form> and </form> tags. All input fields have the following attributes in
common:



type


This attribute specifies the type of the input field: wheth
er it is text, radio or
checkbox



name
-

The name attribute will assign a name for a variable that will hold the entered or
the selected choice.



value


The value attribute assigns a default value for the input field


Submit and Reset Buttons



An input of t
ype submit button is most necessary in a form. It is this control which is
basically a button when clicked sends the data of the form to the URL specified in the
action attribute of the form tag

<input type=”submit” value=”Send Data”



An input of type Rese
t button is used to clear the input fields and give them the default
values.

<input type=”reset” value=”Send Data”


Receiving the data in the form



Depending on the method used in the form, there are three ways in which the data entered
in the form can be
accessed.



GET : The data sent using GET is always URL encoded i.e. data is attached with the
URL. The data’s name/value are separated by & and spaces are replaced by +. The URL
encoded data follows a ? After the name of the script.



The advantages of this m
ethod are simplicity and speed. The disadvantages are that less
data can be passed and the information is displayed in the browser, which can be a
security problem in some situations. processform.php?name=Rama&age=30



POST: The form data is passed as a package in a separate communication with the
processing script. The advantages of this method are unlimited information passing and
security of the data. The disadvantages are the additional overhead and slower speed.



If

GET method is used, all the name/data pairs are available in the global $_GET[] array.
This is an associative array and the value of an input field in the form is obtained by
giving the name of the field as index.



If POST method is used, $_POST[] can be u
sed.



The data sent using both GET and POST are available in the $_REQUEST[] array.


Adding text fields



<input type = “text” name = “number”>



Here type of the input field is “text”



Name of the input text field is “number” which acts as variable that holds
the value
entered in the text field

Ex: In the form


Enter a number <input type =“text” name = “num”>

In PHP, the value entered in the text field can be accessed as $value = $_REQUEST[‘num’];


Handling text area



Text areas are used for multiline text inpu
t



Input tag:


<textarea name = “text” cols = 50 rows = 5>


</textarea>



In PHP


$data = $_REQUEST[‘text’];


Handling Check Boxes



These are square shaped controls that can be selected or deselected with a mouse. These
are used typically when we want the use
r to give input in terms of Yes/No.



<input type = “checkbox” name = “check” value=“Yes”>


The string specified for the value attribute “Yes” is sent to the PHP script with the form
data and the value can be accessed through the name attribute “check”



The
value of the checkbox can be accessed only if the checkbox has been ticked. We can
check whether the check box has been ticked using the isset() function. The isset function
takes a variable name as parameter and checks whether the variable exists or not.



PHP script:



If(isset($_REQUEST[‘check’]))



echo $_REQUEST[‘check’];


else



echo “Checkbox was not ticked”;



Handling Radio Buttons




Check boxes are useful if we want the user to select multiple items from a number of
choices.



Radio buttons are useful
if we want user to select only one item from a number of choices



All the radio buttons that form a group should have the same name attribute



<input type = “radio” name = “sex” value = “Male”>



<input type = “radio” name = “sex” value = “Female”>


PHP: if(
isset($_REQUEST[‘sex’]))




echo “You are a $_REQUEST[‘sex’]”;



Handling list boxes



A list box allows a user to make a choice from a list of already available choices



A <select> tag is used for a list box



We can allow the user to make a single selection
or multiple selection



For single selection:


<select name=“op”>



<option>add</option>



<option>sub</option>


</select>

In the PHP side $_REQUEST[‘op’] will give the selection made namely add or sub



For multiple selection

<select name = “op[]” multiple>



<option>add</option>



<option>sub</option>

</select>

In the PHP side $_REQUEST[‘op’] returns an array of the selections made. We can iterate
through the array and process the selections made. When multiple selections are allowed, we
have to specify the m
ultiple attribute of the select tag and the name for the control should end
with square brackets. This indicates that that the user can make multiple selections.


Password and Hidden fields



Password field <input type=“password” name = “pwd”>



Hidden fields

: Hidden fields are used to store information about a user and these fields
are not visible. They simple store data.


<input type = “hidden” name = “hide”>


The values in these fields are accessed in the same manner as the values of text fields


Adding su
bmit button



Submit button is used to send the data entered in the form to the file that has been
mentioned in the action attribute of the form tag. When this button is pressed, the data in
the form is sent to the server.



The input type of submit button is
“submit”



The value given to the value attribute is displayed on the button



Ex:<input type = “submit” value = “Send” name = “but”>

The PHP script can access the value of the button by specifying the name of the button in
$_POST array as index. $_POST[‘but’]


PHP Server variables



PHP has a super global array $_SERVER which contains necessary information about
our web application can retrieve the name of script under execution, the server host name,
port number, the browser type of the user and other such deta
ils



$_SERVER[‘SERVER_NAME’]


gives host name



$_SERVER[‘SERVER_PORT’]


gives the port number of the server where the script
was accessed



$_SERVER[‘PHP_SELF’]


gives the name of the PHP script currently under execution

$_SERVER[‘HTTP_USER_AGENT’] gives th
e browser type. The string returned by this will
contain the string MSIE for IE and Firefox for Mozilla firefox. The string can be checked for
these two strings to determine the browser type.


Redirecting browser



The browser can be redirected to a new URL

using the header function



The header function takes a string as a parameter which is the new URL where the
browser must be redirected to

header($newURL). Upon execution of this line the browser will display the page whose URL is
given in the parameter $ne
wURL


Dumping all form data at once



All the data in the form can be displayed by using the foreach loop that processes the
$_REQUEST array element by element.

If the element in the $_REQUEST array is itself an array (for example multiple selection), then
the element can be checked whether it is an array by the function is_array($arr). If the element is
an array, then the element can be processed using another loop to display its contents


Handling form data with custom arrays



If we want to group all the da
ta in the form with a single name, then in the form’s
input field tags, the name of the input field is given as arrname[fieldname]



Ex: <input type=“text” name = “data[name]”>




<input type = “text” name = “data[age]”>

In the script side, the form data
is accessed as $_REQUEST[‘data’]. This returns an associative
array. Then, the associative arrays elements form the different form input fields




Putting form data and processing in a single PHP file



Till not we have used to files, one html file for getting

input from the user and one
PHP script to process the input.



We do not need two separate files, one for showing the input controls and the other
for processing data. Both these can be clubbed in
to

a single
PHP
file



The single PHP script
takes care of both displaying the input controls and also
process them.



When both display and processing are combined in a single script, the user has to
access the same URL for both the purposes. The PHP script must be capable of
identifying whether the
user is accessing the URL for the first time, in which case it
must display the form or whether the URL is being accessed after the form has been
submitted in which case it must process the form data.



The PHP script distinguishes between these two accesses

through the use of a hidden
field. If the URL is being accessed for the first time, then the hidden field will not be
set and the form must be displayed. But if the URL is being accessed after the form
submission, then the hidden field will be set and the

user can process the form data.


Example: Combining display and processing in a single PHP script

Script file name : phpcombined.php

<?php


if(!isset($_REQUEST[‘page_seen’])) // hidden field not set display form


{



display_form();


}


else


{



process
_form();


}



function display_form()


{



echo “<form action = ‘phpcombined.php’ method=
\
”POST
\
”><br>”;



echo “<input type =
\
”text
\
” name =
\
”name
\
”><br>”;



echo “<input type =
\
”text
\
” name =
\
”age
\
”><br>”;



echo “<input type =
\
”submit
\
” value =
\
”GO
\
”><br>”;



echo “</form>”;


}

function process_form()

{


echo “Your name is $_REQUEST[‘name’]<br>”:


echo “Your age is $_REQUEST[‘age’]<br>”:

}

?>


Performing Data Validation


The process of checking whether the user has given all the necessary data i
n the nedded
correct format and reporting errors if any is called as data validation.


Data validation is typically performed after the user the has submitted the form and
before any processing can begin on the data. A global error array is maintained whic
h stores all
the error identified in the given data. Before the input data is processed, the error array is
checked for any entries. If the error array has more then zero entries, then it implies that there
have been errors in the input and the errors are
displayed and the form shown again to the user to
given correct input. The general structure for performing Data Validation is as given below. In
the example given below, check_error() function checks for any errors in the input and the
display_error() fun
ction displays the errors to the user.


<?php


$err_arr = array();


if(!isset($_REQUEST[‘page_seen’])) // hidden field not set display form


{



display_form();


}


else


{



check_error();



if(count($err_arr)>0)



{




display_error();




display_form()
;



}



process_form();


}



function display_form()


{



echo “<form action = ‘phpcombined.php’ method=
\
”POST
\
”><br>”;



echo “<input type =
\
”text
\
” name =
\
”name
\
”><br>”;



echo “<input type =
\
”text
\
” name =
\
”age
\
”><br>”;



echo “<input type =
\
”submit
\
” value =
\
”GO
\
”><br>”;



echo “</form>”;


}


function process_form()

{


echo “Your name is $_REQUEST[‘name’]<br>”:


echo “Your age is $_REQUEST[‘age’]<br>”:

}


function check_error()

{


global $err_arr;


//Check for errors and add elements to $er
r_arr on finding errors

}


function display_error()

{


//Process error array and display errors

}

?>


Checking whether the user has entered the required data


To check whether the user has entered all the required data, each of the entered form data
is
checked against the empty string “”. If the user has left an input field empty, then comparison
against the empty string will succeed and an entry is made in the error array. For the example
given above, we can check whether the user has entered the ‘name’

and ‘age’ field values
correctly by implementing the check_error() function as follows. In the check_error() function,
the $err_arr array must be declared global since we use the same array that has been declared
outside the function in the main body of t
he PHP script.


function check_error()

{


global $err_arr;


if($_REQUEST[‘name’] == “”)



$err_arr[] = “Enter your name”;


if($_REQUEST[‘age’] == “”)



$err_arr[] = “Enter your age”;

}

Requiring number input


In the example above, we have asked the user to

enter his age which must be a number.
To check whether the user has indeed given a numeric input, we convert the value entered by the
user to an integer and again back to string and compared the converted string to the original
string value. If the origin
al string value and the converted value are same, then the user has given
numerical input else input is not in the correct form. To convert string to integer, we use the
intval() inbuilt PHP function and to convert integer to string we use the strval() fun
ction. The
example given below checks whether the user has given correct numerical input for the age field.
The check_error() function is modified accordingly.


function check_error()

{


global $err_arr;


if($_REQUEST[‘name’] == “”)



$err_arr[] = “Enter y
our name”;


if($_REQUEST[‘age’] == “”)



$err_arr[] = “Enter your age”;


else if(strcmp($_REQUEST[‘age’], strval(intval($_REQUEST[‘age’]))))



$err_arr = “Please enter an integer”;

}


Persisting user data


In many cases, a form shown to the user has many
controls and user commits errors in
entering data in certain controls while data in certain other controls may be appropriate. Before
processing the data, our script checks for errors and when we display the errors, we would still
want to display the corre
ct data that the users have entered so that the user need not start all over
again for every single error committed by him. To achieve this whenever we display the form,
we set the value of the input field either from the value entered by the user if the u
ser has
submitted the form or set it to the empty string if the user is viewing the form for the first time.
While setting the value of an input field we make use of the fact that, if the user is viewing the
form after submitting the form due to errors, th
en the input field values will be set. If the user is
viewing the form for the first time, then the values will not be set. This method of displaying the
data entered by the user again back to him in the form is known as persistence of user data. To
accomp
lish this, the display_form() function is modified accordingly.



function display_form()


{



$name = isset($_REQUEST[‘name’]) ? $_REQUEST[‘name’] : ””;



$age = isset($_REQUEST[‘age’]) ? $_REQUEST[‘age’] : “”;



echo “<form action = ‘phpcombined.php’ met
hod=
\
”POST
\
”><br>”;



echo “<input type =
\
”text
\
” name =
\
”name
\
” value =
\
”$name
\
”><br>”;



echo “<input type =
\
”text
\
” name =
\
”age
\
” value =
\
”$age
\
”><br>”;



echo “<input type =
\
”submit
\
” value =
\
”GO
\
”><br>”;



echo “</form>”;


}


UNIT III


OBJECT

ORIENTED PROGRAMMING IN PHP

1.CLASSES AND OBJECTS


1.1 Definitions


1.1.1. Objects
:


Objects are tangible real world entities which can be either physical or conceptual. They
have a set of attributes/characteristics and a well defined behavior.

Example:car, person, stack, bank
-
account


1.1.2. Classes
:


A class serves a template or pattern using which objects of that type are created. The
class defines the properties, the attributes of the object. It also defines the things the object can
do


its

responsibilities.


1.1.3. Properties
:


Objects have properties also called attributes which distinguish one object from the other.
Properties of an object are stored as class variables inside the class definition. The values of the
properties of an object

can change over time.

Example: For a car object, its color, model , registration number can form its attributes. Similarly
for a circle object, its radius forms its property because the radius is what distinguishes one circle
from the other.


1.1.4. Metho
ds
:


The things objects can do are sometimes referred to as responsibilities. Each thing an
object can do


each responsibility


is programmed into the class and called a method.

Example: a car object can move forward, stop, backup, and park. Similarly, g
iven a circle object,
we can obtain its circumference, area. These also form the methods of the circle class.


Methods form the interface of an object to the outside world.


1.1.5. Inheritance
:


The method by which objects share the properties and methods
of other similar objects
and add their own special behavior and attributes is called as inheritance.


The class that contains common attributes and behavior is called as the super class and
the class that extends the functionality of the super class is cal
led as sub class.


PHP supports single inheritance that is a class can extend the functionality of only one
class and not more than one class.


1.2. OOP concepts that PHP omits


Polymorphism: We cannot define two different functions with the same name in
PHP
unlike in other object oriented languages.


Multiple Inheritance: An object cannot inherit the behavior of more then one class.


1.3. Defining a class


1.3.1. Writing the class statement


We write the class statement to define the properties and method
s for the class. The class
statement has the following general format:

class
className

{

Add statements that define the properties

Add all the methods

}


The classname can be any valid PHP identifier except stdClass as this name is used
internally.

Example: Creating a class called square

class Square

{

}


1.3.2. Adding properties:


When defining a class, all the properties are declared in the top of the class, as follows:

class classname

{

var $varname;

Method statements

}



In PHP variable declaratio
ns are not necessary. Similarly, in a class, object variables need
not be declared but for clarity it is better to declare the variables.



Default values can be given to the class variables but the default values must be simple
values and not the result of
any computation. Example var $num=10 is allowed but

var $num=20 + 67 is not allowed



An array is allowed in the variable declaration, as long as the values are simple, as
follows: var $doors = array(“front”,”back”);

Example: Setting properties for the
square class

class Square

{


var $side;

}



1.3.3. Using the class variables inside the class


To use the variables defined in a class in a class method a special variable $this must be
used. $this is a variable that refers to the object whose variables a
re being used in the method.


$this can be used only inside a class and not outside. The format for accessing a class
variable using $this is $this
-
>varname. The varname should not be preceded by $ while using
with $this.


1.3.4. Adding methods


i)

Defining a

Constructor

The
constructor
is a special method that is executed when an object is created using the
class as a pattern. A constructor is not required, and a constructor need not be used if we don’t
want to set any property values or perform any actions w
hen the object is created. Only one
constructor is allowed. If we do not define our own constructor, then a default constructor is
provided by PHP.

The constructor has a special name so that PHP knows to execute the method when an
object is created. Constr
uctors are named __construct. (Note the two underscores.) A constructor
method looks similar to the following:

function __construct()

{

$this
-
>varname = 10;

}

Example: Adding a constructor to Square class

class Square

{


var $side;



function
__constructor($s)


{



$this
-
>side = $s;


}

}


ii)

Adding other methods


Methods define what an object can do and are written in the class by using the function
format. Parameters can be passed and values can be returned.

Example: Adding a area() and perimeter
() method to the Square class

class Square

{


var $side;



function __constructor($s)


{



$this
-
>side = $s;


}



function area()


{



return $this
-
>side * $this
-
>side;


}



function perimeter()


{



return 4*$this
-
>side;


}


}

area() method: Finds the
area of the square and returns it

perimeter() method: Finds the perimeter of the square and returns it.


1.4 Using a class


The class definition must be available to the script that needs to use the class. This is
done usually by defining the class in a se
parate file and including the file in the script that needs
to use it. A file can be included by using the include function. Its format is
include(“filename.php”);


1.4.1. Creating an object:


Once a class definition is available, an object can be created
as follows if we have a user
defined constructor with parameters.

$objectname = new
classname
(value,value,...);



If we do not define an constructor in the class, then an object is created as follows:

$objectname = new
classname
;


Creating an object is als
o called instantiating an object. Without creating an object, none
of the methods can be used.

Example: creating a square object


include("SquareClass.php");




$sq1 = new Square(5);



$sq2 = new Square(3);


SquareClass.php contains the Square class
definition. The above statements create two squares
$sq1 and $sq2 with initial values of 5 and 3.


1.4.2. Using the class methods:


Once we create square objects, its methods can be accessed as follows:


$area = $sq1
-
>area();


$peri = $sq1
-
>perimeter();


e
cho “The area of square 1 is $area”;


echo “The perimeter of square 1 is $peri”;


1.5. Access modifiers
-

Public and Private


Access modifiers are keywords that determine how and who can access the properties
and methods of an object. There are three acces
s modifiers, namely, public, private and
protected. Public and private are discussed here while protected will be discussed later.


Public
:

Public means that methods or properties inside the class can be accessed by any function
outside the class definitio
n.. The default access of methods and properties is public.

Example:

class Car

{


var $color;

}

$mycar = new Car;

echo $mycar
-
>color;


The color variable can be accessed from outside the class because of var declaration.


Private
:


We can prevent access to

properties by making them private. The properties or methods
if made private cannot be accessed from outside the class, either by the script or from another
class.

Example:

class Car

{


private $color;

}

$mycar = new Car;

echo $mycar
-
>color;

will give a f
atal error. Private variable $color cannot be accessed from outside the class.


1.6. Destroying an object:


An object can be destroyed by using the unset function. Unset($objname) destroys the
object $objname.


Destructor
:


A method that is called when an
object is destroyed is called a destructor. A destructor is
typically used to free up valuable computing resources. A destructor can be added in a class by
defining a function called __destruct() in the class. The format is as follows:

function __destruct(
)

{

}


1.7. Inheritance


The process by which a class (child/derived) inherits the properties and functionality of
another class (base/parent) and can optionally add/modify the properties and functionality is
called inheritance. Whenever a class extends
another class, all the properties and methods of the
parent class become a part of the child class. But the child class cannot directly access any of the
privately defined properties or methods of the parent class. The child class can only access public
an
d protected properties and methods. Apart from the properties and methods inherited, the child