KEMBAR78
Unit-6 Web Technology | PDF | Object Oriented Programming | Class (Computer Programming)
0% found this document useful (0 votes)
7 views24 pages

Unit-6 Web Technology

The document provides an overview of server-side programming with PHP, detailing its capabilities such as generating dynamic web pages, interacting with databases, and handling user data. It introduces object-oriented programming concepts in PHP, including classes, objects, inheritance, and encapsulation, along with examples of defining classes and creating objects. Additionally, it covers PHP syntax, variables, operators, and control structures, emphasizing the flexibility and power of PHP for web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views24 pages

Unit-6 Web Technology

The document provides an overview of server-side programming with PHP, detailing its capabilities such as generating dynamic web pages, interacting with databases, and handling user data. It introduces object-oriented programming concepts in PHP, including classes, objects, inheritance, and encapsulation, along with examples of defining classes and creating objects. Additionally, it covers PHP syntax, variables, operators, and control structures, emphasizing the flexibility and power of PHP for web development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Page |1

Unit-6 Server Side Programming with PHP


Introduction to server-side programming
The server side programming is the name given to all types of programs which run on the web
server. They process the user input, interact with the databases and control what content is
served back to the client as a response to his request. It is written in a number of programming
languages including PHP, NodeJS, Python, etc and has full access to the server’s OS and the
programmer can chose the language he/she wants to code in.
Server-side programming is extremely useful as it helps to efficiently deliver user-customised
content, and thus enhance the user experience. It can also be used to refine responses based on
the user’s data (Data Analysis).

PHP Basics, Object oriented Concept


What is PHP?
PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-used open source server-
side scripting language to write dynamically generated web pages. PHP scripts are executed on
the server and the result is sent to the browser as plain HTML.
PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
PHP can be embedded within a normal HTML web pages. That means inside our HTML documents
We'll have PHP statements like this:
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Application</title>
</head>
<body>
<?php
// Display greeting message
echo 'Hello World!';
?>
</body>
</html>

Jhalnath Chapagain | GM COLLEGE


Page |2

What we can do with PHP?

• We can generate dynamic pages and files.


• We can create, open, read, write and close files on the server.
• We can collect data from a web form such as user information, email, credit card
information and much more.
• We can send emails to the users of our website.
• We can send and receive cookies to track the visitor of our website.
• We can store, delete, and modify information in database.
• We can restrict unauthorized access to our website.
• We can encrypt data for safe transmission over internet.

Object oriented concept in PHP


Procedural programming is about writing procedures or functions that perform operations on
the data, while object-oriented programming is about creating objects that contain both data
and functions.
The structure, or building blocks, of object-oriented programming include the following:

• 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.

Jhalnath Chapagain | GM COLLEGE


Page |3

• Destructor − refers to a special type of function which will be called automatically


whenever an object is deleted or goes out of scope.

PHP is a flexible platform in terms of accessing member functions and variables.Object-oriented


programming in PHP helps developers build reusable and complex web applications. Object-
oriented programming is a programming style that refers to the association of various
components and revolves around the inheritance, polymorphism, encapsulation, and abstraction
concepts.
OOP is programmed in such a way that the users can focus on the object while developing the
program and code, but not the procedure. OOP also focuses on drawing programming close to
real life.
Defining PHP Classes
The general form for defining a new class in PHP is as follows −

<?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/>";
}

Jhalnath Chapagain | GM COLLEGE


Page |4

function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>

Creating Objects in PHP


Once you defined your class, then you can create as many objects as you like of that class type.
Following is an example of how to create object using new operator.

$physics = new Books;

//Where $physics is an object and Books is a class.

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;
}
}

$apple = new Fruit();


$apple->set_name('Apple'); //function call
$apple->set_color('Red');

Jhalnath Chapagain | GM COLLEGE


Page |5

echo "Name: " . $apple->get_name(); //function call


echo "<br>";
echo "Color: " . $apple->get_color(); //function call
?>

Embedding PHP scripts


PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like you do
in regular HTML pages as well as embed PHP codes for server side execution.
Example

<!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;

Jhalnath Chapagain | GM COLLEGE


Page |6

//variable Example
<?php
// Declaring variables
$txt="Hello World!";
$number=10;

// Displaying variables value


echo $txt; // Output: Hello World!
echo $number; // Output: 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:

Operator Description Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y.

* Multiplication $x * $y Product of $x and $y.

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

Jhalnath Chapagain | GM COLLEGE


Page |7

//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
?>

2. PHP Assignment Operators


The assignment operators are used to assign values to variables.

Operator Description Example Is The Same As

= Assign $x = $y $x = $y

+= Add and assign $x += $y $x = $x + $y

-= Subtract and assign $x -= $y $x = $x - $y

*= Multiply and assign $x *= $y $x = $x * $y

/= Divide and assign quotient $x /= $y $x = $x / $y

%= Divide and assign modulus $x %= $y $x = $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

Jhalnath Chapagain | GM COLLEGE


Page |8

$x=5;
$x*=25;
echo$x; // Outputs: 125

$x=50;
$x/=10;
echo$x; // Outputs: 5

$x=100;
$x%=15;
echo$x; // Outputs: 10
?>

3. PHP Comparison Operators


The comparison operators are used to compare two values in a Boolean fashion.

Operator Name Example Result

== Equal $x == $y True if $x is equal to $y

=== Identical $x === $y True if $x is equal to $y, and they are of the same type

!= Not equal $x != $y True if $x is not equal to $y

<> Not equal $x <> $y True if $x is not equal to $y

!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the
same type

< Less than $x < $y True if $x is less than $y

> Greater than $x > $y True if $x is greater than $y

>= Greater than or equal to $x >= $y True if $x is greater than or equal to $y

<= Less than or equal to $x <= $y True if $x is less than or equal to $y

Jhalnath Chapagain | GM COLLEGE


Page |9

//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
?>

4. PHP Logical Operators


The logical operators are typically used to combine conditional statements.

Operator Name Example Result

and And $x and $y True if both $x and $y are true

or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $$x or $y is true

! Not !$x True if $x is not true

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{

Jhalnath Chapagain | GM COLLEGE


P a g e | 10

echo"$year is not a leap year.";


}
?>

5. PHP String Operators


There are two operators which are specifically designed for strings.

Operator Description Example Result

. Concatenation $str1 . $str2 Concatenation of $str1 and $str2

.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1

//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

define(name, value, case-insensitive)

Jhalnath Chapagain | GM COLLEGE


P a g e | 11

Example

Create a constant with a case-sensitive name:

<?php
define("GREETING", "Welcome!");
echo GREETING;
?>

Example

Create a constant with a case-insensitive name:

<?php
define("GREETING", "Welcome", true);
echo greeting;
?>

Control structures in PHP

The Control Structures (or) Statements used to alter the execution process of a program.

These statements are mainly categorized into following:

• 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

(Write syntax of each yourself :- just like C program)

Jhalnath Chapagain | GM COLLEGE


P a g e | 12

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";
}
?>

Jhalnath Chapagain | GM COLLEGE


P a g e | 13

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.

In PHP, the following are loop statements

• while loop
• do - while loop
• for loop
• for-each loop

Jhalnath Chapagain | GM COLLEGE


P a g e | 14

//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>

Jhalnath Chapagain | GM COLLEGE


P a g e | 15

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

The foreach loop is used to iterate over arrays.

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");

// Loop through colors array


foreach($colors as $value){
echo $value . "<br>";
}
?>

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.

In PHP, the following are jump statements

• break statement

Jhalnath Chapagain | GM COLLEGE


P a g e | 16

• 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.

Jhalnath Chapagain | GM COLLEGE


P a g e | 17

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.

Jhalnath Chapagain | GM COLLEGE


P a g e | 18

Syntax:

function fun_name ()
{
//code
}

Simple Function

function without any arguments or parameters.

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;

Jhalnath Chapagain | GM COLLEGE


P a g e | 19

echo "Sum is :$sum <br/>";


}
add(23,34);//calling function

function sub($a,$b) //function defn


{
$sub = $a - $b;
echo "Sub is :$sub";
}
sub(63,34);//calling function
?>
</body>
</html>

PHP Built-in Functions

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.

Some useful php in-built functions are:

• echo()
• print()
• printf()
• mysqli_connect()
• strlen()
• phpinfo()
• usort()
etc.

PHP User-defined Functions

It is possible in PHP to create our own functions, such functions are called user-defined functions.

A function has the following characteristics:

• can be used repeatedly in a program.


• will not be executed automatically when a page loads
• can be executed by a function call

Creating a function in PHP uses the following syntax:

function functionName() {

code to be executed;

Jhalnath Chapagain | GM COLLEGE


P a g e | 20

<?php

function helloWorld() {
echo "Hello world! <br>";
}

helloWorld(); //function call


?>

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>

String Manipulation in PHP


PHP provides many built-in functions for manipulating strings like calculating the length of a string, find
substrings or characters, replacing part of a string with different characters, take a string apart, and many
others. Here are the examples of some of these functions.

Jhalnath Chapagain | GM COLLEGE


P a g e | 21

Calculating the Length of a String


The strlen() function is used to calculate the number of characters inside a string. It also includes the blank
spaces inside the string.
Example
<?php
$my_str='Welcome to php;

// Outputs: 28
echo strlen($my_str);
?>

Counting Number of Words in a String

The str_word_count() function counts the number of words in a string.


Example
<?php
$my_str='The quick brown fox jumps over the lazy dog.';

// Outputs: 9
echo str_word_count($my_str);
?>

Replacing Text within Strings

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.';

// Display replaced string


echo str_replace("facts", "truth", $my_str);
?>

The output of the above code will be:


If the truth do not fit the theory, change the truth.

Jhalnath Chapagain | GM COLLEGE


P a g e | 22

Reversing a String
The strrev() function reverses a string.
Example
<?php
$my_str='You can do anything, but not everything.';

// Display reversed string


echo strrev($my_str);
?>
?>

Regular expression in PHP

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
?>

Jhalnath Chapagain | GM COLLEGE


P a g e | 23

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";

Jhalnath Chapagain | GM COLLEGE


P a g e | 24

}
finally{
echo “<br>Statements inside finally block always executes”;
}
// Continue execution
?>

Output:
Caught exception: Division by zero.
Statements inside finally block always executes.

PHP Exception Object


The Exception object has the following methods:
Method Description
getCode() Returns the exception code
getFile() Returns the full path of the file in which the
exception was thrown
getMessage() Returns a string describing why the exception
was thrown
getLine() Returns the line number of the line of code which
threw the exception

Jhalnath Chapagain | GM COLLEGE

You might also like