Unit-6 Web Technology
Unit-6 Web Technology
• Classes are user-defined data types that act as the blueprint for individual objects,
attributes and methods.
• Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or an abstract entity. When class is defined initially, the
description is the only object that is defined.
• Member Variable- These are basically the variables that are designed inside a class. Once
an object is created, member variables are also referred to as the attributes of that object.
• Member Function- As the name suggests itself, member functions refer to the functions
that are defined inside a class and used to access object data.
• Inheritance − When a class is defined by inheriting existing function of a parent class then
it is called inheritance. Here child class will inherit all or few member functions and
variables of a parent class.
• 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.
• Data Abstraction − Any representation of data in which the implementation details are
hidden (abstracted).
• Encapsulation − refers to a concept where we encapsulate all the data and member
functions together to form an object.
• Constructor − refers to a special type of function which will be called automatically
whenever there is an object formation from a class.
<?php
class phpClass {
var $var1;
var $var2 = "constant string";
function myfunc ($arg1, $arg2) {
//statements
}
}
?>
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/>";
}
}
?>
Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_color($color) {
$this->color = $color;
}
function get_color() {
return $this->color;
}
}
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>A Simple PHP File</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>
The above example shows how we can embed PHP codes within HTML to create well-formed
dynamic web pages.
Basic syntax (Variables, operators, expressions, constants)
Variables in php
Variables are used to store data, like string of text, numbers, etc. Variable values can change over
the course of a script. Here're some important things to know about variables:
• In PHP, a variable does not need to be declared before adding a value to it. PHP
automatically converts the variable to the correct data type, depending on its value.
• After declaring a variable it can be reused throughout the code.
• The assignment operator (=) used to assign value to a variable.
• In PHP variable can be declared as: $var_name = value;
//variable Example
<?php
// Declaring variables
$txt="Hello World!";
$number=10;
Operators in PHP
Operators are symbols that tell the PHP processor to perform certain actions. For example, the
addition (+) symbol is an operator that tells PHP to add two variables or values, while the greater-
than (>) symbol is an operator that tells PHP to compare two values.
The following lists describe the different operators used in PHP.
1. PHP Arithmetic Operators
The arithmetic operators are used to perform common arithmetical operations, such as
addition, subtraction, multiplication etc. Here's a complete list of PHP's arithmetic operators:
//Example
<?php
$x=10;
$y=4;
Echo ($x+$y); // 0utputs: 14
echo($x-$y); // 0utputs: 6
echo($x*$y); // 0utputs: 40
echo($x/$y); // 0utputs: 2.5
echo($x%$y); // 0utputs: 2
?>
= Assign $x = $y $x = $y
//Example
<?php
$x=10;
echo$x; // Outputs: 10
$x=20;
$x+=30;
echo$x; // Outputs: 50
$x=50;
$x-=20;
echo$x; // Outputs: 30
$x=5;
$x*=25;
echo$x; // Outputs: 125
$x=50;
$x/=10;
echo$x; // Outputs: 5
$x=100;
$x%=15;
echo$x; // Outputs: 10
?>
=== Identical $x === $y True if $x is equal to $y, and they are of the same type
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the
same type
//Example
<?php
$x=25;
$y=35;
$z="25";
var_dump($x==$z); // Outputs: boolean true
var_dump($x===$z); // Outputs: boolean false
var_dump($x!=$y); // Outputs: boolean true
var_dump($x!==$z); // Outputs: boolean true
var_dump($x<$y); // Outputs: boolean true
var_dump($x>$y); // Outputs: boolean false
var_dump($x<=$y); // Outputs: boolean true
var_dump($x>=$y); // Outputs: boolean false
?>
Example
<?php
$year=2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year%400==0) || (($year%100!=0) && ($year%4==0))){
echo"$year is a leap year.";
} else{
//Example
<?php
$x="Hello";
$y=" World!";
echo$x . $y; // Outputs: Hello World!
$x .=$y;
echo$x; // Outputs: Hello World!
?>
Expressions in PHP
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is an
expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type $a = 5, you're assigning
5 into $a. 5, obviously, has the value 5, or in other words 5 is an expression with the value of 5 (in this
case, 5 is an integer constant).
Constants in PHP
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A
valid constant name starts with a letter or underscore (no $ sign before the constant name). Unlike
variables, constants are automatically global across the entire script.
Syntax
Example
<?php
define("GREETING", "Welcome!");
echo GREETING;
?>
Example
<?php
define("GREETING", "Welcome", true);
echo greeting;
?>
The Control Structures (or) Statements used to alter the execution process of a program.
• Conditional Statements
• Loop Statements
• Jump Statements
1. Conditional Statements :
Conditional Statements performs different computations or actions depending on conditions. In PHP, the
following are conditional statements
• if statement
• if - else statement
• if - elseif - else statement
• switch statement
Some Examples:
"ConditionalDemo.php"
<html>
<head>
<title>Conditional Demo</title>
</head>
<body>
<?php
$x=15;
$y=5;
if ($x > $y)
{
echo "$x is greater than $y";
}
else if ($x < $y)
{
echo "$x is lessthan $y";
}
else
{
echo "Both are Equal";
}
?>
</body>
</html>
EvenOdd.php
<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
Example: "SwitchDemo.php"
<html>
<head>
<title>Switch Demo</title>
</head>
<body>
<?php
$x=15;
$y=10;
$op='*';
switch($op)
{
case '+': $z = $x + $y;
echo "Addition is : $z";
break;
case '-': $z = $x - $y;
echo "Subtraction is : $z";
break;
case '*': $z = $x * $y;
echo "Multiplication is : $z";
break;
case '/': $z = $x / $y;
echo "Division is : $z";
break;
case '%': $z = $x % $y;
echo "Modulus is : $z";
break;
default: echo "Invalid Operator";
}
?>
</body>
</html>
2. Loop Statements :
Sometimes we may need to alter the flow of the program. If the execution of a specific code may need
to be repeated several numbers of times then we can go for loop statements.
• while loop
• do - while loop
• for loop
• for-each loop
//Example: "WhileDemo.php"
<html>
<head>
<title>While Demo</title>
</head>
<body>
<h1>While Demo</h1>
<?php
$n=1;
while($n<=5)
{
echo "$n <br/>";
$n++;
}
?>
</body>
</html>
Example: "DoWhileDemo.php"
<html>
<head>
<title>Do-While Demo</title>
</head>
<body>
<h1>Do-While Demo</h1>
<?php
$n=1;
do
{
echo "$n <br/>";
$n++;
} while($n<=5);
?>
</body>
</html>
Example: "ForDemo.php"
<html>
<head>
<title>For Demo</title>
</head>
<body>
<h1>For Demo</h1>
<?php
for($i=1;$i<=5;$i++)
{
echo "$i <br/>";
}
?>
</body>
</html>
PHP foreach Loop
foreach($array as $value){
// Code to be executed
The following example demonstrates a loop that will print the values of the given array:
<?php
$colors=array("Red", "Green", "Blue");
3. Jump Statements :
Jump statements in PHP are used to alter the flow of a loop like you want to skip a part of a loop or
terminate a loop.
• break statement
• continue statement
break statement
The break is a keyword in php which is used to bring the program control out of the loop. i.e. when a
break statement is encountered inside a loop, the loop is terminated and program control resumes at
the next statement following the loop.
The break statement breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner
loop first and then proceeds to outer loops. The break is commonly used in the cases where we need to
break the loop for a given condition.
Example: "BreakDemo.php"
<html>
<head>
<title>Break Demo</title>
</head>
<body>
<h1>Break Demo</h1>
<?php
for($i=1;$i<=10;$i++)
{
if($i==5)
{
break; //terminates the current loop
}
echo "$i <br/>";
}
echo "Loop is Over !";
?>
</body>
</html>
Output:
Loop is Over !
continue statement
The continue statement in php is used to bring the program control to the beginning of the loop. i.e.
when a continue statement is encountered inside the loop, remaining statements are skipped and loop
proceeds with the next iteration.
The continue statement skips the remaining lines of code inside the loop and start with the next
iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific
code for a particular condition.
//Example: "ContinueDemo.php"
<html>
<head>
<title>Continue Demo</title>
</head>
<body>
<h1>Continue Demo</h1>
<?php
for($i=1;$i<=10;$i++)
{
if($i%2==0)
{
continue; //terminates the current Iteration and moves to Next
}
echo "$i <br/>";
}
echo "Loop is Over !";
?>
</body>
</html>
Output:
Loop is Over !
PHP functions
A function is a self-contained block of code that performs a specific task. The main advantage of
functions is that code reusability (Write once Invoke multiple).
PHP supports both built-in and user-defined functions. And PHP supports thousands of built-in functions
and allows us to define own functions, by using "function" keyword.
Syntax:
function fun_name ()
{
//code
}
Simple Function
Example: "FunSimple.php"
<html>
<head>
<title>Function Example</title>
</head>
<body>
<h1>Simple Function Example</h1>
<?php
function simple() //Function Definition
{
echo "Welcome to php";
}
simple();//Function calling
?>
</body>
</html>
Parameterized Functions
These functions allow us to pass one or more parameters inside the function. We can pass the information
in function through arguments (or) parameters which are separated by comma (,). These passed
arguments (or) parameters acts as variables inside the function.
Example: "FunParam.php"
<html>
<head>
<title>Function Example</title>
</head>
<body>
<h1>Parameterized Function Example</h1>
<?php
function add($a,$b) //function defn
{
$sum = $a + $b;
The built-in functions are those functions which are derived by the PHP designers. And we can just use
them whenever we feel need of them. PHP has over 1000 built-in functions that can be called directly,
from within a script, to perform a specific task.
• echo()
• print()
• printf()
• mysqli_connect()
• strlen()
• phpinfo()
• usort()
etc.
It is possible in PHP to create our own functions, such functions are called user-defined functions.
function functionName() {
code to be executed;
<?php
function helloWorld() {
echo "Hello world! <br>";
}
Recursive function
PHP allow us to use recursive function. In this case, we call the current function within the same function.
It is also known as recursion.
Example: "FunRecursive.php"
<html>
<head>
<title>Recursive Function Example</title>
</head>
<body>
<h1>Recursive Function Demo</h1>
<?php
function factorial($n)
{
if($n < 0)
return -1;
if($n == 0)
return 1;
return($n * factorial($n - 1));
}
echo factorial(5);
?>
</body>
</html>
// Outputs: 28
echo strlen($my_str);
?>
// Outputs: 9
echo str_word_count($my_str);
?>
The str_replace() replaces all occurrences of the search text within the target string.
Example
<?php
$my_str='If the facts do not fit the theory, change the facts.';
Reversing a String
The strrev() function reverses a string.
Example
<?php
$my_str='You can do anything, but not everything.';
PHP provides a variety of functions that allow us to use regular expressions. The preg_match(),
preg_match_all() and preg_replace() functions are some of the most commonly used ones:
• preg_match()=> Returns 1 if the pattern was found in the string and 0 if not
• preg_match_all()=>Returns the number of times the pattern was found in the string, which may
also be 0
• preg_replace()=>Returns a new string where matched patterns have been replaced with another
string
Using preg_match()
The preg_match() function will tell you whether a string contains matches of a pattern.
Example
Use a regular expression to do a case-insensitive search for "BCAV" in a string:
<?php
$str = "Hello BCAV";
$pattern = "/BCAV/i";
echo preg_match($pattern, $str); // Outputs 1
?>
Using preg_match_all()
The preg_match_all() function will tell you how many matches were found for a pattern in a string.
Example
Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
Using preg_replace()
The preg_replace() function will replace all of the matches of the pattern in a string with another string.
Example
Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:
<?php
$str = "Hello World";
$pattern = "/World/i";
echo preg_replace($pattern, "BCA V", $str); // Outputs "Hello BCAV"
?>
Exception handling
Exception handling is almost similar in all programming languages. It changes the normal flow of the
program when a specified error condition occurs, and this condition is known as exception. PHP offers the
following keywords for this purpose:
try -
The try block contains the code that may have an exception or where an exception can arise. When an
exception occurs inside the try block during runtime of code, it is caught and resolved in catch block. The
try block must be followed by catch or finally block. A try block can be followed by minimum one and
maximum any number of catch blocks.
catch -
The catch block contains the code that executes when a specified exception is thrown. It is always used
with a try block, not alone. When an exception occurs, PHP finds the matching catch block.
throw -
It is a keyword used to throw an exception. It also helps to list all the exceptions that a function throws
but does not handle itself.
Remember that each throw must have at least one "catch".
finally -
The finally block contains a code, which is used for clean-up activity in PHP. Basically, it executes the
essential code of the program.
Example:
<?php
function division($x,$y) {
if ($y==0){
throw new Exception('Division by zero.');
}
return $x/$y;
}
try {
echo division(5,0)."\n";
}
catch (Exception $e) {
echo “Caught exception: ”, $e->getMessage(), "\n";
}
finally{
echo “<br>Statements inside finally block always executes”;
}
// Continue execution
?>
Output:
Caught exception: Division by zero.
Statements inside finally block always executes.