PHP & MySQL Web Development Syllabus
PHP & MySQL Web Development Syllabus
COLLEGE
ADITHYA NAGAR, SPSR NELLORE
Syllabus
Name:
References
1. Julie C. Meloni, SAMS Teach yourself PHP MySQL and Apache, Pearson
Education (2007).
2.Steven Holzner , PHP: The Complete Reference, McGraw-Hill
3. Robin Nixon, Learning PHP, MySQL, JavaScript, CSS & HTML5, Third
Edition O'reilly, 2014
4. Xue Bai Michael Ekedahl, The web warrior guide to Web Programming,
Thomson (2006).
5. Web resources:
e. http://www.codecademy.com/tracks/php
f. http://www.w3schools.com/PHP
g. http://www.tutorialpoint.com
6. Other web sources suggested by the teacher concerned and the college
librarian including reading material.
Unit-1
The Building blocks of PHP
Variables: A variable is a special container that we can define, which then “holds”
a value, such as a number, string, object, array, or a Boolean. Variables are
fundamental to programming. Without variables, we would be forced to write
hard-code each specific value used in our scripts. For example the following hard-
coded statement adds two numbers together and prints the result, which solves a
simple mathematics problem:
echo (2 + 4);
However, this snippet of code is useful only for person, who specifically want to
know the sum of 2 and 4. Similarly, in order to find the sum of two other numbers
say 3 and 5, we have to write one more instruction. That means, each time the
values get changed, we have to write separate instruction. However, this approach
to programming is clearly meaningless, and this is where variables come into play.
Here are the most important things to know about variables in PHP.
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
A PHP variable name cannot contain spaces.
PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
As PHP is a loosely typed language, so we do not need to declare the data types of
the variables. It automatically analyzes the values and makes conversions to its
correct datatype.
Variables in PHP do not have built-in types. That is, a variable does not know in
advance whether it will be used to store a number or a string of characters.
Variables used before they are assigned will have default values.
PHP does a good job of automatically converting types from one to another when
necessary.
After declaring a variable, it can be reused throughout the code.
Better to use short, meaningful and descriptive variable names.
Declaration must be terminated with semi-colon.
PHP variables are Perl-like.
Valid Examples:
$fee;
$a_longish_variable_name;
$subject1;
$stud_name;
Invalid Examples:
Invalid Example Reason
Total Must start with $ symbol.
$total Marks Blank spaces are not allowd.
$2x Variable name must not start with digit.
$a+b-(c+d/2) Special symbols are not allowed.
PHP Global Variables – Superglobals: Some predefined variables in PHP are "superglobals",
which means that they are always accessible, regardless of scope - and you can access them
from any function, class or file without having to do anything special.
The PHP superglobal variables are:
$_GET contains any variables provided to a script through the GET method.
$_POST contains any variables provided to a script through the POST method.
$_COOKIE contains any variables provided to a script through a cookie.
$_FILES contains any variables provided to a script through file uploads.
$_SERVER contains information such as headers, file paths, and script
locations.
$_ENV contains any variables provided to a script as part of the server
environment.
$_REQUEST contains any variables provided to a script via GET, POST, or
COOKIE input mechanisms.
$_SESSION contains any variables that are currently registered in a session.
Data Types: A data type specifies the amount of memory that allocates to a value
associated with it. A type also determines the operations that you can perform on it. PHP
data types are used to hold different types of data or values. PHP supports 8 primitive data
types that can be categorized further in 3 types:
PHP Boolean: Booleans are the simplest data type works like electrical switch. It holds only
two values: TRUE (1) or FALSE (0). It is often used with conditional statements. If the
condition is correct, it returns TRUE otherwise FALSE.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is TRUE.
PHP Integer: Integer means numeric data with a negative or positive sign. It holds only
whole numbers, i.e., numbers without fractional part or decimal points.
Rules for integer:
An integer can be either positive or negative.
An integer must not contain decimal point.
Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 that
is, -231 to 231.
Example:
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float: A floating-point number is a number with a decimal point. Unlike integer, it can
hold numbers with a fractional or decimal point, including a negative or positive sign.
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
Output:
Addition of floating numbers: 73.812
PHP String: A string is a non-numeric data type. It holds letters or any alphabets, numbers,
and even special characters. String values must be enclosed either within single quotes or
in double quotes. But both are treated differently. The following example illustrates this
clearly.
Example:
<?php
$name = "Sai Dhanush";
//both single and double quote statements will be treated as different
echo "Hello $name";
echo "</br>";
echo 'Hello $name';
?>
Output:
Hello Sai Dhanush
Hello $name
PHP Array: An array is a compound data type. It can store multiple values of same data
type in a single variable.
Example:
<?php
$bikes = array ("Royal Enfield", "Yamaha", "Hero");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "Hero" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: Hero
PHP object: Objects are the instances of user-defined classes that can store both values
and functions. They must be explicitly declared.
Example:
<?php
class bike
{
function model()
{
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Bike Model: Royal Enfield
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 11
PHP Resource: Resources are not the exact data type in PHP. Basically, these are used to
store some function calls or references to external PHP resources. For example - a
database call. It is an external resource.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of writing it
in capital letters as it is case sensitive. The special type of data type NULL defined a
variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Output:
Operators and Expressions
Operator: Generally operator is a special symbol or keyword that is used to perform
certain operation. For example in an expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. PHP language supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Arithmetic Operators: There are following arithmetic operators supported by PHP language
− Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition becomes
true.
>= Checks if the value of left operand is greater than or (A >= B) is not
equal to the value of right operand, if yes then true.
condition becomes true.
<= Checks if the value of left operand is less than or equal (A <= B) is true.
to the value of right operand, if yes then condition
becomes true.
<html>
<head>
<title>Comparison Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 20;
if( $a == $b ) {
echo "TEST1 : a is equal to b<br/>";
}else {
echo "TEST1 : a is not equal to b<br/>";
}
if( $a > $b ) {
Logical Operators: There are following logical operators supported by PHP language.
Assume variable A holds 10 and variable B holds 20 then −
Operator Description Example
and Called Logical AND operator. If both the operands are true (A and B) is
then condition becomes true. true.
&& Called Logical AND operator. If both the operands are non (A && B) is
zero then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical !(A && B) is
state of its operand. If a condition is true then Logical false.
NOT operator will make false.
<html>
<head>
<title>Logical Operators</title>
</head>
<body>
<?php
$a = 42;
$b = 0;
if( $a && $b ) {
echo "TEST1 : Both a and b are true<br/>";
}else{
echo "TEST1 : Either a or b is false<br/>";
}
if( $a and $b ) {
echo "TEST2 : Both a and b are true<br/>";
}else{
echo "TEST2 : Either a or b is false<br/>";
}
if( $a || $b ) {
</head>
<body>
<?php
$a = 42;
$b = 20;
$c = $a + $b;
echo "Addtion Operation Result: $c <br/>";
$c += $a;
echo "Add AND Assigment Operation Result: $c <br/>";
$c -= $a;
echo "Subtract AND Assignment Operation Result: $c <br/>";
$c *= $a;
echo "Multiply AND Assignment Operation Result: $c <br/>";
$c /= $a;
echo "Division AND Assignment Operation Result: $c <br/>";
$c %= $a;
echo "Modulus AND Assignment Operation Result: $c <br/>";
?>
</body>
</html>
Output:
Addtion Operation Result: 62
Add AND Assigment Operation Result: 104
Subtract AND Assignment Operation Result: 62
Multiply AND Assignment Operation Result: 2604
Division AND Assignment Operation Result: 62
Modulus AND Assignment Operation Result: 20
Conditional Operator
There is one more operator called conditional operator. This first evaluates an expression
for a true or false value and then execute one of the two given statements depending upon
the result of the evaluation. The conditional operator has this syntax −
Operator Description Example
<html>
<head>
<title>Conditional Operator</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
/* If condition is true then assign a to result otheriwse b */
$result = ($a > $b ) ? $a :$b;
echo "TEST1 : Value of result is $result<br/>";
/* If condition is true then assign a to result otheriwse b */
$result = ($a < $b ) ? $a :$b;
echo "TEST2 : Value of result is $result<br/>";
?>
</body>
</html>
Output:
TEST1 : Value of result is 20
TEST2 : Value of result is 10
Operators Categories:
All the operators can be categorised into following categories −
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of the
first expression.
Assignment operators, which assign a value to a variable.
Precedence of PHP Operators
Operator precedence determines the order of evaluation of operators in an expression.
This affects how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the addition
operator.
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds 7.
Here operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Expressions
Introduction: Almost everything in a PHP script is an expression. Anything that
evaluates/has a value is an expression. In a typical assignment statement ($x=100), a literal
value, a function or operands processed by operators is an expression, anything that
appears to the right of assignment operator (=).
Syntax:
$x=100; //100 is an expression
$a=$b+$c; //$b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression
Expression with ++ and -- operators
These operators are called increment and decrement operators respectively. These are
unary operators, needing just one operand and can be used in prefix or postfix manner,
although with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 whereas -- operator
decrements by 1. However, when used in assignment expression, prefix makes
incremnt/decrement first and then followed by assignment. In case of postfix, assignment
is done before increment/decrement.
Example-1
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
Output
This produces following result
x = 11 y = 10
Example-2
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
Output
This produces following result
x = 11 y = 11
Expression with Ternary conditional operator:
Ternary operator has three operands. First one is a logical expression. If it is TRUE,
second operand expression is evaluated otherwise third one is evaluated.
Example
<?php
$marks=60;
$result= $marks<50 ? "Fail" : "Pass";
echo $result;
?>
Output
Following result will be displayed
Pass
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Note: Only scalar data (boolean, integer, float and string) can be contained in constants.
Differences between constants and variables:
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.
Valid Examples:
// Valid constant names
define("ONE", "first thing");
define("TWO2", "second thing");
define("THREE_3", "third thing");
define("__THREE__", "third value");
Invalid Example:
1 __LINE__
The current line number of the file.
2 __FILE__
The full path and filename of the file. If used inside an include,the name of the
included file is returned. Since PHP 4.0.2, __FILE__ always contains an
absolute path whereas in older versions it contained relative path under some
circumstances.
3 __FUNCTION__
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
function name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.
4 __CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
class name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.
5 __METHOD__
The class method name. (Added in PHP 5.0.0) The method name is returned as it
was declared (case-sensitive).
</html>
b) The If...Else Statement:If we want to execute some code if a condition is true and
another code if a condition is false, we use the if....else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example
The following example will output "Have a nice weekend!" if the current day is Saturday,
Otherwise, it will output "Have a nice day!":
<html>
<body>
<?php
$d = date("D");
if ($d == "Sat")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
Output:
Have a nice weekend!
c) The ElseIf Statement: If we want to execute some code if one of the several
conditions are true use the elseif statement.
Syntax
if (condition)
code to be executed if condition is true;
elseif (condition)
code to be executed if condition is true;
else
If we want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
case label-n:
code to be executed if expression = label-n;
break;
default:
default code to be executed if miss match occurs;
}
Example
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Sorry... Invalid Day! ";
}
?>
</body>
</html>
Output:
Today is Monday
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop
iterations. A variable may be declared here for this purpose and it is traditional to name it
$i.
Example
The following example makes five iterations and changes the assigned value of two variables
on each pass of the loop −
<html>
<body>
<?php
$a = 0;
$b = 0;
for( $i = 0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a = $a and b = $b" );
?>
</body>
</html>
Output:
At the end of the loop a = 50 and b = 25
b) The while loop statement: The while statement will execute a block of code if and as
long as a test expression is true. If the test expression is true then the code block will
be executed. After the code has executed the test expression will again be evaluated and
the loop will continue until the test expression is found to be false.
Syntax
while (condition)
{
code to be executed;
}
Example: This example decrements a variable value on each iteration of the loop and the
counter increments until it reaches 10 when the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;
$num = 50;
c) The do...while loop statement: The do...while statement will execute a block of
code at least once - it then will repeat the loop as long as a condition is true.
Syntax
do
{
code to be executed;
}while (condition);
Example: The following example will increment the value of i at least once, and it will
continue incrementing the variable i as long as it has a value of less than 10 −
<html>
<body>
<?php
$i = 0;
$num = 0;
do
{
$i++;
}
while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Output:
Loop stopped at i = 10
d) The foreach loop statement: The foreach statement is used to loop through arrays.
For each pass the value of the current array element is assigned to $value and the
array pointer is moved by one and in the next pass next element will be processed.
Syntax
foreach (array as value)
{
code to be executed;
}
Example
<html>
<body>
<?php
$array = array( 1, 2, 3, 4, 5);
foreach( $array as $value )
{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Example:
<html>
<body>
<?php
$i = 0;
while( $i < 10) {
$i++;
if( $i == 3 )break;
}
echo ("Loop stopped at i = $i" );
?>
</body>
</html>
Output:
Loop stopped at i = 3
Example: In the following example loop prints the value of array but for which
condition becomes true it just skip the code and next value is printed.
<html>
<body>
<?php
Value is 1
Value is 2
Value is 4
Value is 5
Description
Syntax
In PHP we use {} to wrap code blocks and notify the compiler by saying, "hey this is a group
of statements."
Example
<html>
<head>
<title>Listing 5.13</title>
</head>
<body>
<?php
$display_prices = true;
if ( $display_prices )
{
print "<table border=\"1\">";
print "<tr><td colspan=\"3\">";
print "today's prices in dollars";
print "</td></tr>";
print "<tr><td>14</td><td>32</td><td>71</td></tr>";
print "</table>";
}
?>
</body>
</html>
If the value of $display_prices is set to true in line 2, the table is printed. For the
sake of readability, we split the output into multiple echo() statements, and once
again use the backslash to escape any quotation marks used in the HTML output.
Put these lines into a text file called testmultiecho.php and place this file in web
server’s document root. When we access this script through our web browser, it
should look like as follows.
There’s nothing wrong with the way this is coded, but you can save yourself some
typing by simply slipping back into HTML mode within the code block as follows.
<?php
$display_prices = true;
if ($display_prices)
{ ?>
<table border=”1”>
<tr>
<td colspan=”3”> today’s prices in dollars </td>
</tr>
<tr>
<td>$14.00</td>
<td>$32.00</td>
<td>$71.00</td>
</tr>
</table>
<?php
}
?>
The important thing to note here is that the shift to HTML mode occurs only if
the condition of the if statement is fulfilled. This can save you the bother of
escaping quotation marks and wrapping our output in echo() statements. This
approach might, however, affect the readability of the code in the long run,
espe- cially if the script grows larger.
b) User Defined Functions: Apart from the built-in functions, PHP allows us to create
our own customised functions called the user-defined functions. Using this we can
create our own packages of code and use it wherever necessary by simply calling it.
In fact we hardly need to create our own PHP function because there are already more than
1000 of built-in library functions created for different area and we just need to call them
according to our requirement.
Defining and Calling a PHP Function (User Defined Function): It is very easy to create
our own PHP function. Suppose if we want to create a PHP function which will simply write a
simple message on our browser when we will call it, the following example creates a function
called writeMessage() and then calls it just after creating it. In PHP, while creating a
function its name should start with keyword function and all the PHP code should be put
inside { and } braces as shown in the following example.
Example:
<html>
<head>
<title> Writing PHP Function </title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo " Education Is The Only Weapon That Can Change The Entire World!";
}
/* Calling a PHP Function */
writeMessage();
?>
</body>
</html>
Output:
Education Is The Only Weapon That Can Change The Entire World!
Returning value from User-Defined Functions: A function can return a value using
the ‘return’ statement in conjunction with a value or object. ‘return’ statement stops the
execution of the function and sends the value back to the calling code. We can return more
than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns
their sum to the calling program. Note that return keyword is used to return a value from a
function.
Example:
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
</body>
</html>
Output:
Variable Scope
The scope of a variable is defined as its range in the program under which it can be
accessed. In other words, "The scope of a variable is the portion of the program within
which it is defined and can be accessed."
PHP has three types of variable scopes:
a) Local variable
b) Global variable
c) Static variable
a) Local variable
The variables that are declared within a function are called local variables for that
function. These local variables have their scope only in that particular function in which
they are declared. This means that these variables cannot be accessed outside the function,
as they have local scope.
File: local_variable1.php
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:
Local variable declared inside the function is: 45
[A variable declaration outside the function with the same name is completely different
from the variable declared inside the function. Let's understand the local variables with the
help of an example:
File: local_variable2.php
<?php
function mytest()
{
$lang = "PHP";
echo "Web development language: " .$lang;
}
mytest();
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 42
//using $lang (local variable) outside the function will generate an error
echo $lang;
?>
Output:
Web development language: PHP
Notice: Undefined variable: lang in D:\xampp\htdocs\program\p3.php on line 28]
Global variable: The global variables are the variables that are declared outside the
function. These variables can be accessed anywhere in the program. To access the global
variable within a function, use the GLOBAL keyword before the variable. However, these
variables can be directly accessed or used outside the function without any keyword.
Therefore there is no need to use any keyword to access a global variable outside the
function.
Example:
File: global_variable1.php
<?php
$name = "LuckyMilky"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Variable inside the function: LuckyMilky
Variable outside the function: LuckyMilky
Note: Without using the global keyword, if you try to access a global variable inside the
function, it will generate an error that the variable is undefined.
Using $GLOBALS instead of global
Another way to use the global variable inside the function is predefined $GLOBALS array.
Example:
File: global_variable2.php
<?php
$num1 = 5; //global variable
$num2 = 13; //global variable
function global_var()
{
$sum = $GLOBALS['num1'] + $GLOBALS['num2'];
echo "Sum of global variables is: " .$sum;
}
global_var();
?>
Output:
Sum of global variables is: 18
Note: If two variables, local and global, have the same name, then the local variable has
higher priority than the global variable inside the function.
Example:
File: global_variable3.php
<?php
$x = 5;
function mytest()
{
$x = 7;
echo "value of x: " .$x;
}
mytest();
?>
Output:
Value of x: 7
Static variable: It is a feature of PHP to delete the variable, once it completes its
execution and memory is freed. Sometimes we need to store a variable even after
completion of function execution. Therefore, another important feature of variable scoping
is static variable. We use the static keyword before the variable to define a variable, and
this variable is called as static variable.
Static variables exist only in a local function, but it does not free its memory after the
program execution leaves the scope.
Example:
File: static_variable.php
<?php
function static_var()
{
static $num1 = 3; //static variable
$num2 = 6; //Non-static variable
//increment in non-static variable
$num1++;
//increment in static variable
$num2++;
echo "Static: " .$num1 ."</br>";
echo "Non-static: " .$num2 ."</br>";
}
//first function call
static_var();
//second function call
static_var();
?>
Output:
Static: 4
Non-static: 7
Static: 5
Non-static: 7
In the above example, $num1 regularly increments after each function call, whereas $num2
does not. This is why because $num1 is not a static variable, so it freed its memory after
the execution of each function call.
Saving state between Function calls with the static statement: Variables within
functions have a short but happy life on the whole. They come into being when the function
is called and die when execution is finished. But, if we want a function to keep track of the
number of times it has been called, it can be done in two ways as shown below.
<title>Example</title>
</head>
<body>
<?php
$num_of_calls = 0;
function numberedHeading( $txt )
{
global $num_of_calls;
$num_of_calls++;
print "<h1>$num_of_calls. $txt</h1>";
}
numberedHeading("Widgets");
print("We build a fine range of widgets<p>");
numberedHeading("Doodads");
print("Finest in the world<p>");
?>
</body>
</html>
Put these lines into a text file called numberedheading.php, and place this file in Web
server document root. When we access this script through our Web browser, it should look
like:
PHP gives us option to pass our parameters inside a function. We can pass as many as
parameters we like. These parameters work like variables inside our function. Following
example takes two integer parameters and add them together and then print them.
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Output:
Sum of the two numbers is : 30
<html>
<head>
We can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html>
<head>
<title>Writing PHP Function which returns value</title>
</head>
<body>
<?php
This is test
Dynamic Function Calls: It is possible to assign function names as strings to variables and
then treat these variables exactly as the function name itself. Following example depicts
this behaviour.
<html>
<head>
<title>Dynamic Function Calls</title>
</head>
<body>
<?php
function sayHello()
{
echo "Hello<br />";
}
$function_holder = "sayHello";
$function_holder();
?>
</body>
</html>
Output:
Hello
Unit-II
Working with Arrays
What are Arrays? Types of Arrays?
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its
easy to define an array of 100 length.
Creating Arrays: We can create an array using either the array() function or the
array operator []. The array() function is usually used when we want to create a new
array and populate it with more than one element, all in one attempt. The array
operator is often used when you want to create a new array with just one element
at a time.
Types of Arrays: There are three different kinds of arrays and each array value is
accessed using an ID which is called array index or key.
a) Numeric array
b) Associative array
c) Multidimensional array
a) Numeric Array: These arrays can store numbers, strings and any object but their index
will be represented by numbers. By default array index starts from zero. There are two
ways to create arryas. They are,
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value )
{
echo "Value is $value <br />";
}
For example, to store the salaries of employees in an array, a numerically indexed array
would not be the best choice. Instead, we could use the employees names as the keys in
our associative array, and the value would be their respective salary.
NOTE – We should not keep associative array inside double quotes while printing otherwise
it would not return any value.
Example:
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("Lucky" => 40000, "Milky" => 50000, "Chinnu" => 60000);
c) Multidimensional Arrays: A multi-dimensional array each element in the main array can
also be an array. And each element in the sub-array can be an array, and so on. Values in
the multi-dimensional array are accessed using multiple indexes.
Example: In this example we create a two dimensional array to store marks of three
students in three subjects −
<html>
<body>
<?php
$marks = array(
"Lucky" => array ("C_Lang" => 74,"Java" => 73, "PHP" => 73),
"Milky" => array ("C_Lang" => 73, "Java" => 73,"PHP" => 71),
"Chinnu" => array ("C_Lang" => 31,"Java" => 22,"PHP" => 72)
);
/* Accessing multi-dimensional array values */
echo "Marks for Lucky in C_Lang : " ;
echo $marks['Lucky']['C_Lang'] . "<br />";
echo "Marks for Milky in Java : ";
echo $marks['Milky']['Java'] . "<br />";
echo "Marks for Chinnu in PHP : " ;
echo $marks['Chinnu']['PHP'] . "<br />";
?>
</body>
</html>
Output:
More than 70 array-related functions are built in to PHP, which we can read about
in detail at http://www.php.net/array. Some of the more common (and useful)
func- tions are given below.
a) count() and sizeof(): Each of these functions counts the number of elements in an
array. They are aliases of each other. Consider the following array.
Example: shuffle($existingArray);
Example: reset($character);
This function proves useful when you are performing multiple manipulations on
an array, such as sorting, extracting values, and so forth.
Object Oriented Concepts: Important terms related to Object Oriented Programming are
defined below.
a) Class: This is a programmer-defined data type, which includes local functions as well as
local data. We can think of a class as a template for making many instances of the same
kind (or class) of object.
c) Member Variable: These are the variables defined inside a class. This data will be
invisible to the outside of the class and can be accessed via member functions. These
variables are called attribute of the object once an object is created.
d) Member function: These are the function defined inside a class and are used to access
object data.
e) Inheritance: Deriving a new class from an existing class is called as inheritance. Here
child class will inherit all or few member functions and variables of a parent class.
f) Parent class: A class that is inherited by another class. This is also called a base class or
super class.
g) Child Class: A class that inherited from another class. This is also called a subclass or
derived class.
h) Polymorphism: This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it take different
number of arguments and can do different task.
j) Data Abstraction: Any representation of data in which the implementation details are
hidden (abstracted).
k) Encapsulation: Refers to a concept where we encapsulate(bind) all the data and member
functions together to form an object.
Defining PHP Classes: The general form for defining a new class in PHP is as follows.
Syntax:
<?php
class ClassName
{
DataMembers/Field declarations;
MemberFunctions/methods;
}
?>
In the above syntax,
‘class’ is a keyword, followed by the name of the class that you want to define.
The curly braces indicate beginning and ending of class definition. And class
definition includes variable declarations and function definitions.
Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a constant
value.
Function definitions look much like standalone PHP functions but are local to the class
and will be used to set and access object data.
Example: Here is an example which defines a class of Books type.
<?php
class Books
{
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par)
{
$this->price = $par;
}
function getPrice()
{
echo $this->price ."<br/>";
}
function setTitle($par)
{
$this->title = $par;
}
function getTitle()
{
echo $this->title ." <br/>";
}
}
?>
The variable $this is a special variable and it refers to the same object ie. itself.
Creating Objects in PHP Once we defined our class, then we can create as many objects as
we like of that class type. Following is an example of how to create object
using new operator.
$C_Programming = new Books;
$OOP_Through_Java = new Books;
$DataStructures = new Books;
Here we have created three objects and these objects are independent of each other and
they will have their existence separately.
Calling Member Functions: After creating objects, we can call member functions related to
that object. One member function will be able to process member variable of related object
only. Following example shows how to set title and prices for the three books by calling
member functions.
$C_Programming->setTitle( "C_Programming for Data Science" );
$DataStructures->setTitle( " DataStructures" );
$OOP_Through_Java->setTitle( "Java for Data Science" );
$C_Programming->setPrice( 1000 );
$DataStructures->setPrice( 1500 );
$OOP_Through_Java->setPrice( 1300 );
Now we can call another member functions to get the values set by in above example as
follows.
$C_Programming->getTitle();
$DataStructures->getTitle();
$OOP_Through_Java->getTitle();
$C_Programming->getPrice();
$DataStructures->getPrice();
$OOP_Through_Java->getPrice();
This will produce the following output:
C_Programming for Data Science
DataStructures
Java for Data Science
1000
1500
1300
Constructor Functions: Constructor Functions are special type of functions which are
called automatically whenever an object is created. So we take full advantage of this
behaviour, by initializing many things through constructor functions.
Following example will create one constructor for Books class and it will initialize price and
title for the book at the time of object creation.
$DataStructures->getTitle();
$OOP_Through_Java->getTitle();
$C_Programming->getPrice();
$DataStructures->getPrice();
$OOP_Through_Java->getPrice();
This will produce the following output:
{
echo $this->publisher. "<br />";
}
}
Now apart from inherited functions, class Course keeps two additional member functions.
Function Overriding: Function definitions in child classes override definitions with the
same name in parent classes. In a child class, we can modify the definition of a function
inherited from parent class.
In the following example getPrice and getTitle functions are overridden to return some
values.
function getPrice()
{
echo $this->price . "<br/>";
return $this->price;
}
function getTitle()
{
echo $this->title . "<br/>";
return $this->title;
}
Public Members: Unless we specify otherwise, properties and methods of a class are public.
That is to say, they may be accessed in three possible situations −
From outside the class in which it is declared
From within the class in which it is declared
From within another class that implements the class in which it is declared
We need not to declare all the members as public, if we need to limit the accessibility of
the members of a class then we define class members as private or protected.
Private members: By designating a member private, we limit its accessibility to the class in
which it is declared. The private member cannot be referred to from classes that inherit
the class in which it is declared and cannot be accessed from outside the class.
class MyClass
{
private $safe = "secured"; // available only with in the class.
$common = "unsecured"; // can be used even outside the classs
function __construct($par)
{
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() // public method can be used every where
{
return("I'm visible!");
}
private function myPrivateFunction()// private, can be used within the class
{
return("I'm not visible outside!");
}
}
Example:
class MyClass
{
protected $p = "safe";
$q = "unsafe";
function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}
Constants
A constant is somewhat like a variable, in that it holds a value, but is really more like a
function because a constant is immutable. Once we declare a constant, it does not change.
Declaring one constant is easy, as is done in this version of MyClass −
class MyClass
{
const PIE = 3.14;
function __construct($incomingValue) {
// Statements here run every time
// an instance of the class
// is created.
}
}
In this class, PIE is a constant. It is declared with the keyword const, and under no
circumstances can it be changed to anything other than 3.14. Note that the constant's name
does not have a leading $, as variable names do.
Abstract Classes: An abstract class is one that cannot be instantiated, only inherited. We
can declare an abstract class with the keyword abstract.
When inheriting from an abstract class, all methods marked abstract in the parent's class
declaration must be defined by the child; additionally, these methods must be defined with
the same visibility.
Static Keyword: Declaring class members or methods as static makes them accessible
without needing an instantiation of the class. A member declared as static can not be
accessed with an instantiated class object (though a static method can).
Example:
<?php
class Test
{
public static $my_static = 'fun';
public function staticValue()
{
return self::$my_static;
V.Srinivasulu, Dept. of Computer Science, Mail:[email protected]
Mobile:9966074430
OM SAIRAM 68
}
}
print Test::$my_static . "\n";
$t = new Test();
print $t->staticValue() . "\n";
?>
Final Keyword
PHP 5 introduces the final keyword, which prevents child classes from overriding a method
by prefixing the definition with final. If the class itself is being defined final then it cannot
be extended.
<?php
class BaseClass
{
public function test()
{
echo "BaseClass::test() called<br>";
}
final public function moreTesting()
{
echo "BaseClass::moreTesting() called<br>";
}
}
class ChildClass extends BaseClass
{
public function moreTesting()
{
echo "ChildClass::moreTesting() called<br>";
}
}
?>
Calling parent constructors: Instead of writing an entirely new constructor for the
subclass, we can write it by calling the parent's constructor explicitly and then doing
whatever is necessary in addition for instantiation of the subclass.
Example:
class Name
{
var $_firstName;
var $_lastName;
In this example, we have a parent class (Name), which has a two-argument constructor, and
a subclass (NameSub1), which has a three-argument constructor. The constructor of
NameSub1 functions by calling its parent constructor explicitly using the :: syntax (passing
two of its arguments along) and then setting an additional field. Similarly, NameSub1
defines its non constructor toString() function in terms of the parent function that it
overrides.