Chapter 5 Server Side Scripting (PHP)
Chapter 5 Server Side Scripting (PHP)
1. Introduction to PHP?
PHP is the abbreviation of Hypertext Preprocessor and earlier it was abbreviated as Personal Home
Page. It is a general-purpose programming language used to design a website or web application.
It is the server-side scripting language embedded with HTML to develop Static website, Dynamic
website, or Web applications. It was created by Rasmus Lerdorf in 1994. The syntax of PHP is
similar to C, C++, and Java. It manages the dynamic content, database, session, cookies, etc of a
dynamic website.
The websites like www.facebook.com, www.yahoo.com are also built on PHP. It can be easily
embedded with HTML files and HTML codes can also be written in a PHP file. The thing that
differentiates PHP and HTML is, PHP codes are executed on the server whereas HTML codes are
directly rendered on the browser. PHP codes are first executed on the server and then the result is
returned to the browser. The only information that the client or browser knows is the result returned
after executing the PHP script on the server and not the actual PHP codes present in the PHP file.
Also, PHP files can support other client-side scripting languages like CSS and JavaScript. It is
integrated with a number of popular databases such as MySQL, Oracle, Microsoft SQL Server and
others.
2. Features of PHP
Advantages of PHP
Disadvantages of PHP
o Since PHP is open-source so its code is visible to all programmers. If any bugs exist in
the source code then its weakness can be explored by other programmers.
o It is not suitable for large applications because its maintenance is difficult.
o The error handling of a PHP framework is not good.
3. Basic PHP syntax
Scripting in PHP
Example
if (CGPA = = 4) {
print("Excellent");
print("This result is your best effort<br>");
}
PHP is whitespace insensitive: - it almost never matters how many whitespace characters,
tabs, and carriage returns you have in a row.
PHP is case sensitive:- Example the php variables $gradepoint and $Gradepoint are
different variables
PHP comments
There are two commenting formats in PHP: - Single-line and Multi-line comment
Comment type syntax Example
<?php <?php
All variables in PHP are denoted with a leading dollar sign ($).
Variables are assigned with the = operator.
Variables can, but do not need, to be declared before assignment
Variables in PHP do not have intrinsic types
Variables used before they are assigned have default values
PHP automatically convert variable types from one to another when necessary
else
Variable Scope
PHP variables can be one of four scope types
Local variables
Function parameters
Global variables
Static variables
Variable Naming
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores but you cannot use
characters like + , - , % , ( , ) . & , etc
Using strings in php
Example
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
Example
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
The strlen() function is used to find the length of a string
Example
<?php
echo strlen("Internet Programing");
?>
The strpos() function is used to search for a string or character within a string
Example
<?php
echo strpos("Internet Programing", "Programing");
?>
4. Retrieve data from html forms
Dynamic websites provide the functionalities that can use to store, update, retrieve, and delete the
data in a database. A form is a document that containing black fields, that the user can fill the data
or user can select the data and the data will store in the data base. There are two ways the browser
client can send information to the web server. These are the GET and the POST method.
GET Method
GET method sends the encoded user information appended to the page request.
Example
<?php
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "GET">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
POST Method
The POST method transfers information via HTTP headers
data sent by POST method goes through HTTP header so security depends on
HTTP protocol
Example
<?php
if( $_POST["name"] || $_POST["age"] ) {
if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
die ("invalid name and name should be alpha");
}
echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
Name: <input type = "text" name = "name" />
Age: <input type = "text" name = "age" />
<input type = "submit" />
</form>
</body>
</html>
5. Displaying errors
Error handling is the process of catching errors raised by your program and then taking
appropriate action.
o The above error level can be set using following PHP built-in library function
error_function(error_level,error_message, error_file,error_line,error_context);
o Once you define your custom error handler you need to set it using PHP built-in
library set_error_handler function
Example: - the following PHP code handle an error for function calling which does
not exist
<?php
error_reporting( E_ERROR );
function handleError($errno, $errstr,$error_file,$error_line) {
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
PHP supports the two main control structures: conditional statements and repetition statements
I. Conditional statements
Conditional statements uses in a code to make a decisions. PHP supports following three
decision making statements.
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
7. Arrays
An array is a data structure that stores one or more similar type of values in a single value. In PHP,
there are three different kind of arrays and each array value is accessed using an array index.
An array with strings as index. It stores element values in association with key
values rather than in a strict linear index order. Consider the following example
8. Functions
PHP function is a piece of code which takes one or more input in the form of parameter and does
some processing and returns a value. PHP has more than 1000 built-in functions like fopen(),
fread(), print() etc, but it gives you option to create your own functions as well.
Creating PHP Function
o While creating a function in PHP, the function name should start with keyword
function
o All the PHP code should be put inside { and } braces
Example
<?php
function writeMessage() {
echo "Welcome To Werabe University, We Are Glad For Your Coming!";
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
Passing Arguments by Reference
o It is possible to pass arguments to functions by reference by adding an ampersand
(&) to the variable name in either the function call or the function definition
Example
<?php
function addFive($num) {
$num += 5;
}
function addSix(&$num) {
$num += 6;
}
$orignum = 10;
addFive( $orignum );
Example
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?>
9. Form Processing using PHP
HTML forms are used to send the user information to the server and returns the result back to the
browser. For example, if you want to get the details of visitors to your website, and send them
good thoughts, you can collect the user information by means of form processing. Then, the
information can be validated either at the client-side or on the server-side. The final result is sent
to the client through the respective web browser. To create a HTML form, form tag should be
used.
Attribute Description
It specifies the name of the form and is used to identify individual
name or id
forms.
Attribute Description
Textbox allows the user to provide single-line input, which can be
Textbox
used for getting values such as names, search menu and etc.
Textarea allows the user to provide multi-line input, which can be
Textarea
used for getting values such as an address, message etc.
Dropdown or combobox allows the user to provide select a value from
DropDown
a list of values.
Radio buttons allow the user to select only one option from the given
Radio Buttons
set of options.
Checkbox allows the user to select multiple options from the set of
CheckBox
given options.
Buttons Buttons are the clickable controls that can be used to submit the form
All the form controls given above is designed by using the input tag based on the type attribute of
the tag. In the below script, when the form is submitted, no event handling mechanism is done.
Event handling refers to the process done while the form is submitted. These event handling
<html>
<head>
<title>Simple Form Processing</title>
</head>
<body>
<form id="form1" method="post">
FirstName:
<input type="text" name="firstname" required/>
<br>
<br>
LastName
<input type="text" name="lastname" required/>
<br>
<br>
Address
<input type="text" name="address" required/>
<br>
<br>
Email Address:
<input type="email" name="emailaddress" required/>
<br>
<br>
Password:
<input type="password" name="password" required/>
<br>
<br>
<input type="submit" value="Submit”/>
Above HTML script is rewritten using the above mentioned functions and array. The rewritten
script validates all the form fields and if there are no errors, it displays the received information in
a tabular form.
Example
<head>
<title>Simple Form Processing</title>
</head>
<body>
A PHP script can be used with a HTML form to allow users to upload files to the server. Initially
files are uploaded into a temporary directory and then relocated to a target destination by a PHP
script.
Information in the phpinfo.php page describes the temporary directory that is used for file uploads
as upload_tmp_dir and the maximum permitted size of files that can be uploaded is stated as
upload_max_filesize. These parameters are set into PHP configuration file php.ini
o The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
o The user clicks the browse button and selects a file to upload from the local PC.
o The full path to the selected file appears in the text filed then the user clicks the submit
button.
o The selected file is sent to the temporary directory on the server.
o The PHP script that was specified as the form handler in the form's action attribute checks
that the file has arrived and then copies the file into an intended directory.
o The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail. An
uploaded file could be a text file or image file or any document.
Let’s make an HTML form for uploading the file to the server index.html.
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h2>Upload File</h2>
<label for="fileSelect">Filename:</label>
<!-- name of the input fields are going to be used in our php script-->
</form>
</body>
</html>
Now, time to write a php script which is able to handle the file uploading system. file-upload-
manager.php
<?php
$file_name = $_FILES["photo"]["name"];
$file_type = $_FILES["photo"]["type"];
$file_size = $_FILES["photo"]["size"];
if (!array_key_exists($ext, $allowed_ext))
if (file_exists("upload/".$_FILES["photo"]["name"]))
else
move_uploaded_file($_FILES["photo"]["tmp_name"],
"uploads/".$_FILES["photo"]["name"]);
else
else
?>
In the above script, once we submit the form, later we can access the information via a PHP
superglobal associative array $_FILES. Apart from using the $_FILES array, many in-built
functions are playing a major role. After we are done with uploading a file, in the script we will
check the request method of the server, if it is POST then it will proceed otherwise the system will
throw an error. Later on, we have accessed the $_FILES array to get the file name, file size, and
type of the file. Once we got those pieces of information, then we validate the size and type of the
file. In the end, we search in the folder, where the file is to be uploaded, for checking if the file
already exists or not. If not, we have used move_uploaded_file() to move the file from temporary
location to the desired directory on the server and we are done.
A cookie in PHP is a small file with a maximum size of 4KB that the web server stores on the
client computer. They are typically used to keep track of information such as a username that the
site can retrieve to personalize the page when the user visits the website next time. A cookie can
only be read from the domain that it has been issued from. Cookies are usually set in an HTTP
header but JavaScript can also set a cookie directly on a browser.
To set a cookie in PHP, the setcookie() function is used. The setcookie() function needs to be
called prior to any output generated by the script otherwise the cookie will not be set.
Syntax
The setcookie() function requires six arguments in general which are described in the following
table.
Parameters Description
Creating Cookies
The following example describes the creation of the cookie in PHP. The cookie is named
Auction_Item and assigning the value Luxury Car to it. The cookie will expire after 2 days(2 days
* 24 hours * 60 mins * 60 seconds).
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>
It is always advisable to check whether a cookie is set or not before accessing its value. Therefore
to check whether a cookie is set or not, the PHP isset() function is used. To check whether a cookie
“Auction_Item” is set or not, the isset() function is executed as follows:
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
For accessing a cookie value, the PHP $_COOKIE super global variable is used. It is an associative
array that contains a record of all the cookies values sent by the browser in the current request. The
records are stored as a list where the cookie name is used as the key. To access a cookie named
“Auction_Item”, the following code can be executed.
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>
</body>
</html>
Deleting Cookies
The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie()
function is called by passing the cookie name and other arguments or empty strings but however
this time, the expiration date is required to be set in the past. To delete a cookie named
“Auction_Item”, the following code can be executed.
The same path, domain, and other arguments should be passed that were used to create the cookie
in order to ensure that the correct cookie is deleted.
Disadvantages of cookies
Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to easily
modify the content of the cookie. Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.
When you work with an application, you open it, do some changes, and then you close it. This is
much like a session. The computer knows who you are. It knows when you start the application
and when you end. But on the internet there is one problem: the web server does not know who
you are or what you do, because the HTTP address does not maintain state. Session variables solve
this problem by storing user information to be used across multiple pages (e.g. username, favorite
color, etc.). By default, session variables last until the user closes the browser.
A session is used to save information on the server momentarily so that it may be utilized across
various pages of the website. It is the overall amount of time spent on an activity. The user session
begins when the user logs in to a specific network application and ends when the user logs out of
the program or shuts down the machine.
Session values are far more secure since they are saved in binary or encrypted form and can only
be decoded at the server. When the user shuts down the machine or logs out of the program, the
session values are automatically deleted. We must save the values in the database to keep them
forever.
A session creates a file in a temporary directory on the server where registered session variables
and their values are stored. This data will be available to all pages on the site during that visit. The
location of the temporary file is determined by a setting in the php.ini file called session.save_path.
Before using any session variable make sure you have setup this path.
o PHP first creates a unique identifier for that particular session which is a random string of
32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
o A cookie called PHPSESSID is automatically sent to the user's computer to store unique
session identification string.
When a PHP script wants to retrieve the value from a session variable, PHP automatically gets the
unique session identifier string from the PHPSESSID cookie and then looks in its temporary
directory for the file bearing that name and a validation can be done by comparing both values. A
session ends when the user loses the browser or after leaving the site, the server will terminate the
session after a predetermined period of time, commonly 30 minutes duration.
A PHP session is easily started by making a call to the session_start() function. This function first
checks if a session is already started and if none is started then it starts one. It is recommended to
put the call to session_start() at the beginning of the page. Session variables are stored in
associative array called $_SESSION[]. These variables can be accessed during lifetime of a
session.
The following example starts a session then register a variable called counter that is incremented
each time the page is visited during the session. Make use of isset() function to check if session
variable is already set or not.
<?php
session_start();
$_SESSION['counter'] += 1;
}else {
$_SESSION['counter'] = 1;
?>
<html>
<head>
</head>
<body>
</body>
</html>
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session variable then you can use unset() function to unset a session variable.
<?php
unset($_SESSION['counter']);
?>
Here is the call which will destroy all the session variables
<?php
session_destroy();
?>
You do not need to call start_session() function to start a session when a user visits your site
if you can set session.auto_start variable to 1 in php.ini file.
There may be a case when a user does not allow to store cookies on their machine. So there is
another method to send session ID to the browser. Alternatively, you can use the constant SID
which is defined if the session started. If the client did not send an appropriate session cookie,
it has the form session_name=session_id. Otherwise, it expands to an empty string. Thus, you
can embed it unconditionally into URLs.The following example demonstrates how to register
a variable, and how to link correctly to another page using SID.
<?php
session_start();
if (isset($_SESSION['counter'])) {
$_SESSION['counter'] = 1;
}else {
$_SESSION['counter']++;
echo ( $msg );
?>
<p>
</p>
Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing
the corresponding key to the $_SESSION associative array. The PHP code to access a session data
with two session variables Rollnumber and Name is shown below.
<?php
session_start();
?>
Important Points
Database is a collection of inter-related data which helps in efficient retrieval, insertion and
deletion of data from database and organizes the data in the form of tables, views, schemas, reports
etc. For Example, university database organizes the data about students, faculty, and admin staff
etc. which helps in efficient retrieval, insertion and deletion of data from it.
A database is a separate application that stores a collection of data. Each database has one or more
distinct APIs for creating, accessing, managing, searching and replicating the data it holds. Other
Nowadays, we use relational database management systems (RDBMS) to store and manage huge
volume of data. This is called relational database because all the data is stored into different tables
and relations are established using primary keys or other keys known as Foreign Keys.
RDBMS Terminology
Before we proceed to explain the MySQL database system, let us revise a few definitions related
to the database.
MySQL is the most popular Open Source Relational SQL database management system. MySQL
is one of the best RDBMS being used for developing web-based software applications. It is the
most popular database system used with PHP. MySQL is developed, distributed, and supported
by Oracle Corporation.
o The data in a MySQL database are stored in tables which consists of columns and rows.
o MySQL is a database system that runs on a server.
o MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
o MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
o MySQL is very friendly to PHP, the most appreciated language for web development.
o MySQL is ideal for both small and large applications.
o MySQL is very fast, reliable, and easy to use database system. It uses standard SQL
o MySQL compiles on a number of platforms.
o MySQL supports large databases, up to 50 million rows or more in a table. The default
file size limit for a table is 4GB, but you can increase this (if your operating system can
handle it) to a theoretical limit of 8 million terabytes (TB).
12.2 Creating Database Connection in PHP
PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This
function takes six parameters and returns a MySQL link identifier on success or FALSE on failure.
Syntax
Parameters Description
You can disconnect from the MySQL database anytime using another PHP function close().
Syntax
$mysqli->close();
Example-1
<html>
<head>
<title>Connecting MySQL Server</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass);
if($mysqli->connect_errno ) {
printf("Connect failed: %s<br />", $mysqli->connect_error);
Database operations in PHP are a very crucial thing that is especially needed in CRUD (Create,
Read, Update and Delete) operations. Here we will discuss the Read part i.e. data fetching from
database.
Connecting to a Database: You have two options to connect with MySQL database
1. MySQLi Object-Oriented
2. MySQLi Procedural
Executing Queries
After connecting to the database we need to run queries to fetch data. In Read operations, we will
use only select queries to fetch data from the database.
MySQLi Object-Oriented
$conn->query($query);
MySQLi Procedural
mysqli_query($conn, $query)
Close Connection
After the fetching is performed, you should close the connection to the database using the close()
function.
$conn->close();
Example: Create the following sample database and create table in the database
<?php
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "StudentDataBase";
// CREATE CONNECTION
if ($conn->connect_error) {
// SQL QUERY
$result = $conn->query($query);
if ($result->num_rows > 0)
while($row = $result->fetch_assoc())
$row["Age"]. "<br>";
else {
$conn->close();
?>
<?php
$servername = "localhost";
$username = "root";
$password = "";
// CREATE CONNECTION
$conn = mysqli_connect($servername,
if (!$conn) {
// SQL QUERY
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
} else {
$conn->close();
?>
File handling is needed for any application. For some tasks to be done file needs to be processed.
File handling in PHP is similar as file handling is done by using any programming language.
Functions Description
PHP fopen() function is used to open a file. First parameter of fopen() contains
name of the file which is to be opened and second parameter tells about mode in
which file needs to be opened.
Files can be opened in any of the following modes :
o “w” – Opens a file for write only. If file not exist then new file is created
and if file already exists then contents of file is erased.
o “r” – File is opened for read only.
o “a” – File is opened for write only. File pointer points to end of file.
Existing data in file is preserved.
o “w+” – Opens file for read and write. If file not exist then new file is
fopen()
created and if file already exists then contents of file is erased.
o “r+” – File is opened for read/write.
o “a+” – File is opened for write/read. File pointer points to end of file.
Existing data in file is preserved. If file is not there then new file is
created.
o “x” – New file is created for write only.
Example
<?php
$file = fopen(“demo.txt”,'w');
?>
After file is opened using fopen() the contents of data are read using fread(). It
takes two arguments. One is file pointer and another is file size in bytes.
Example
fread() <?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
Date and time are some of the most frequently used operations in PHP while executing SQL
queries or designing a website etc. PHP serves us with predefined functions for these tasks.
Some of the predefined functions in PHP for date and time are discussed below.
The PHP date() function converts timestamp to a more readable date and time format.
Syntax:
Explanation
o The format parameter in the date() function specifies the format of returned date and
time.
o The timestamp is an optional parameter, if it is not included then the current date and
time will be used.
Example: The below program explains the usage of the date() function in PHP.
<?php
$today = date("d/m/Y");
echo $today;
?>
The format parameter of the date() function is a string that can contain multiple characters allowing
to generate the dates in various formats. Date-related formatting characters that are commonly
used in the format string:
o d: Represents day of the month; two digits with leading zeros (01 or 31).
o D: Represents day of the week in the text as an abbreviation (Mon to Sun).
o m: Represents month in numbers with leading zeros (01 or 12).
o M: Represents month in text, abbreviated (Jan to Dec).
o y: Represents year in two digits (08 or 14).
o Y: Represents year in four digits (2008 or 2014)
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.),
slashes (/), or spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
echo date("d.M.Y/D");
?>
The following characters can be used along with the date() function to format the time string:
Example: The below example explains the usage of the date() function in PHP.
<?php
?>
The time() function is used to get the current time as a Unix timestamp (the number of seconds
since the beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
Example: The below example explains the usage of the time() function in PHP.
<?php
echo "\n";
?>
The mktime() function is used to create the timestamp for a specific date and time. If no date and
time are provided, the timestamp for the current date and time is returned.
Syntax:
Example: The below example explains the usage of the mktime() function in PHP.
<?php
?>
The above code creates a time stamp for 25th Nov 2017,23 hrs 21mins 50secs.
Inheritance
In a simple word, inheritance means inheriting the properties or functionalities from one class to
another class. Model and volume will find in all kinds of television but suppose you need to add
additional feature timer. The timer cannot be included in all the television. So it will use inheritance
for that television which includes timer property. Use ‘extends’ keyword to implement inheritance.
Public: Public functions or variables can only be accessed from anywhere. In all the above
examples, we are able to access the public functions and variables outside the class and
everyone can call it.
Private: Private functions or variables can only be accessed by the class who created it.
Example
<?php
// Class definition
class TV {
Protected functions or variables can only be used by the class who created and it’s child class
means all the classes which inherit the property of parent class having protected method or
variable.
Example:
<?php
// Class definition
class TV {
// Member variables
Like the keyword is saying, Abstract means not completed. Abstract classes are those classes
where functions are declared but not implemented.
Example
// Abstract class
}
Output
// Create new object
Welcome to Computer Science
$obj = new def;
echo $obj->xyz();
?>
Interfaces
There is a limitation for inheritance in PHP that is you cannot extend multiple classes. Through
Interface you can achieve multiple inheritance property. Interfaces also worked like abstract
classes. The ‘implements’ keyword is used for interfaces. There is a difference between abstract
class and interface class. In abstract class define variables but in the interface, the class cannot
define variables. It can also not create constructor function in interfaces. It cannot declare a private
or protected function.
Example
<?php
interface a {
Polymorphism means many types or many forms. It means suppose you have created an interface
also classes that will implement this interface class. These classes will have different functionality
and they all will share this common interface.
<?php
interface LoggerInterface {
<?php
class EmailLogger implements LoggerInterface {
public function log($message) {
echo "Logging message to email: $message";
}
}
?>
Create another file FileLogger.php and implement the interface class.
<?php
?>
<?php
Now, create a UserProfile.php file where call all these files by only defining interface name using
type hinting. Do not need to define the class name for calling each and every class created in a file.
<?php
class UserProfile {
private $logger;
$this->logger->log("User Created");
$this->logger->log("User Updated");
$this->logger->log("Deleting User");
$this->logger = $logger;
<?php
function __autoload($class) {
// classes is a directory where all
// the above files are placed.
include_once "classes/$class.php";
}
function getLogger($type) {
switch($type) {
case 'email':
return new EmailLogger();
break;
case 'database':
return new DBLogger();
break;
case 'file':
return new FileLogger();
break;
}
}
$logger = getLogger('database');
$profile = new UserProfile($logger);
$profile->createUser(); ?>