CHAPTER 1-INTRODUCTION TO SERVER-SIDE PROGRAMMING - PHP
CHAPTER 1-INTRODUCTION TO SERVER-SIDE PROGRAMMING - PHP
A scripting language is a language that interprets scripts at runtime. Scripts are usually embedded into
other software environments.
The purpose of the scripts is usually to enhance the performance or perform routine tasks for an
application.
Server side scripts are interpreted on the server while client side scripts are interpreted by the client
application.
PHP is a server side script that is interpreted on the server while JavaScript is an example of a client side
script that is interpreted by the client browser. Both PHP and JavaScript can be embedded into HTML
pages.
What is PHP?
PHP is the most popular server-side scripting language for creating dynamic web pages. PHP stands for
Hypertext Preprocessor. PHP is a very popular and widely-used open source server-side scripting language to
write dynamically generated web pages. PHP was originally created by Rasmus Lerdorf in 1994. It was initially
known as Personal Home Page.
PHP scripts are executed on the server and the result is sent to the web browser as plain HTML.
PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Microsoft
SQL Server, Sybase, and so on. The current major version of PHP is 7.
All of the code in this document has been tested and validated against the most recent release of PHP 7.
PHP is very powerful language yet easy to learn and use.
1
The list does not end here, there are many other interesting things that you can do with PHP. You will learn about
all of them in detail in upcoming sections.
If you're familiar with other server-side languages like ASP.NET or Java, you might be wondering what makes
PHP so special. There are several advantages why one should choose PHP.
Easy to learn: PHP is easy to learn and use. For beginner programmers who just started out in web
development, PHP is often considered as the preferable choice of language to learn.
Open source: PHP is an open-source project. It is developed and maintained by a worldwide community
of developers who make its source code freely available to download and use.
Portability: PHP runs on various platforms such as Microsoft Windows, Linux, Mac OS, etc. and it is
compatible with almost all servers used today such Apache, IIS, etc.
Fast Performance: Scripts written in PHP usually execute or runs faster than those written in other
scripting languages like ASP, Ruby, Python, Java, etc.
Vast Community: Since PHP is supported by the worldwide community, finding help or documentation
related to PHP online is extremely easy.
Tip: Do you know some huge websites like Facebook, Yahoo, Flickr, and Wikipedia are built using PHP. Most of
the major content management systems (CMS), such as WordPress, Drupal, Joomla and Magento are also built in
PHP.
PHP Syntax
PHP Variables
PHP Constants
PHP Echo and Print
PHP Data Types
PHP Strings
PHP Operators
PHP If…Else, PHP Switch…Case, PHP Loops
PHP Arrays
PHP Functions
PHP Classes and Objects
PHP Exception Handling
Install Wampserver or LAMP or MAMP or XAMPP on your PC to quickly create web applications with Apache,
PHP and a MySQL database. Here, you will learn how easy it is to create dynamic web pages using PHP. Before
begin, be sure to have a code editor and some working knowledge of HTML and CSS.
PHP script execute on a web server running PHP. So before you start writing any PHP program you need the
following program installed on your computer.
2
The Apache Web server, The PHP engine, The MySQL database server
You can either install them individually or choose a pre-configured package for your operating system like Linux
and Windows. Popular pre-configured package are XAMPP and WampServer.
WampServer is a Windows web development environment. It allows you to create web applications with
Apache2, PHP and a MySQL database. It will also provide the MySQL administrative tool PhpMyAdmin to
easily manage your databases using a web browser.
The official website for downloading and installation instructions for the WampServer:
http://www.wampserver.com/en/
Now you have successfully installed WampServer on your computer. In this section we will create a very simple
PHP script that displays the text "Hello, world!" in the browser window.
Ok, click on the WampServer icon somewhere on your Windows task bar and select the "www directory".
Alternatively, you can access the "www" directory through navigating the C:\wamp\www. Create a subdirectory
in "www" directory let's say "project". Now open up your favorite code editor and create a new PHP file then type
the following code:
<?php
echo "Hello, world!"; // Display greeting message
?>
Now save this file as "hello.php" in your project folder (located at C:\wamp\www\project), and view the
result in your browser through visiting this URL: http://localhost/project/hello.php.
Alternatively, you can access the "hello.php" file through selecting the localhost option and then select the project
folder from the WampSever menu on the taskbar.
PHP can be embedded within a normal HTML web page. That means inside your HTML document you can write
the PHP statements, as demonstrated in the following example:
<!DOCTYPE HTML>
<html> <head>
<title>PHP Application</title>
</head>
<body>
<?php
echo 'Hello World!'; // Display greeting message
?>
</body></html>
PHP Syntax
A PHP script starts with the <?php and ends with the ?> tag. The PHP delimiter <?php and ?> in the following
example simply tells the PHP engine to treat the enclosed code block as PHP code, rather than simple HTML.
<?php
3
echo "Hello, world!"; // Some code to be executed
?>
Every PHP statement end with a semicolon (;) — this tells the PHP engine that the end of the current statement
has been reached.
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Simple PHP File</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>
The above example shows how you can embed PHP codes within HTML to create well-formed dynamic web
pages. If you view the source code of the resulting web page in your browser, the only difference you will see is
the PHP code <?php echo "Hello, world!"; ?> has been replaced with the output "Hello, world!".
What happens here is? When you run this code the PHP engine executed the instructions between the <?php
… ?> tags and leave rest of the thing as it is. At the end the web server send the final output back to your browser
which is completely in HTML.
PHP Comments
A comment is simply text that is ignored by the PHP engine. The purpose of comments is to make the code more
readable. It may help other developer (or you in the future when you edit the source code) to understand what you
were trying to do with the PHP.
PHP supports single-line as well as multi-line comments. To write a single-line comment either start the line with
either two slashes (//) or a hash symbol (#). For example:
<?php
// This is a single line comment
# This is also a single line comment
echo "Hello, world!";
?>
However to write multi-line comments, start the comment with a slash followed by an asterisk (/*) and end the
comment with an asterisk followed by a slash (*/), like this:
<?php
/*
This is a multiple line comment block
that spans across more than
one line
4
*/
echo "Hello, world!";
?>
Variable names in PHP are case-sensitive. As a result the variables $color, $Color and $COLOR are treated as
three different variables.
<?php
// Assign value to variable
$color = "blue";
// Try to print variable value
echo "The color of the sky is " . $color . "<br>";
echo "The color of the sky is " . $Color . "<br>";
echo "The color of the sky is " . $COLOR . "<br>";
?>
If you try to run the above example code it will only display the value of the variable $color and produce the
"Undefined variable" warning for the variable $Color and $COLOR.
However the keywords function and classes names are case-insensitive. As a result calling the gettype() or
GETTYPE() produce the same result.
<?php
// Assign value to variable
$color = "blue";
// Get the type of a variable
echo gettype($color) . "<br>";
echo GETTYPE($color) . "<br>";
?>
If you try to run the above example code both the functions gettype() and GETTYPE() gives the same
output, which is: string.
PHP Variables
What is Variable 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.
<?php
// Declaring variables
$txt = "Hello World!";
5
$number = 10;
// Displaying variables value
echo $txt; // Output: Hello World!
echo $number; // Output: 10
?>
In the above example we have created two variables where first one has assigned with a string value and the
second has assigned with a number. Later we've displayed the variables values in the browser using the echo
statement. The PHP echo statement is often used to output data to the browser.
All variables in PHP start with a $ sign, followed by the name of the variable.
A variable name must start with a letter or the underscore character _.
A variable name cannot start with a number.
A variable name in PHP can only contain alpha-numeric characters and underscores (A-z, 0-9, and
_).
A variable name cannot contain spaces.
Note: Variable names in PHP are case sensitive, it means $x and $X are two different variables. So be careful
while defining variable names.
PHP Constants
What is Constant in PHP?
A constant is a name or an identifier for a fixed value. Constant are like variables, except that once they are
defined, they cannot be undefined or changed (except magic constants).
Constants are very useful for storing data that doesn't change while the script is running. Common examples of
such data include configuration settings such as database username and password, website's base URL, company
name, etc.
Constants are defined using PHP's define() function, which accepts two arguments: the name of the constant,
and its value. Once defined the constant value can be accessed at any time just by referring to its name. Here is a
simple example:
<?php
// Defining constant
define("SITE_URL", "https://www.google.com/");
// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>
The output of the above code will be: Thank you for visiting - https://www.google.com/
Tip: By storing the value in a constant instead of a variable, you can make sure that the value won't get changed
accidentally when your application runs.
6
Name of constants must follow the same rules as variable names, which means a valid constant name must starts
with a letter or underscore, followed by any number of letters, numbers or underscores with one exception: the $
prefix is not required for constant names.
Note: By convention, constant names are usually written in uppercase letters. This is for their easy identification
and differentiation from variables in the source code.
Moreover PHP provides a set of special predefined constants that change depending on where they are used.
These constants are called magic constants. For example, the value of __LINE__ depends on the line that it's
used on in your script.
Magic constants begin with two underscores and end with two underscores. The following section describes some
of the most useful magical PHP constants.
__LINE__
The __LINE__ constant returns the current line number of the file, like this:
<?php
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 2
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 3
echo "Line number " . __LINE__ . "<br>"; // Displays: Line number 4
?>
__FILE__
The __FILE__ constant returns full path and name of the PHP file that's being executed. If used inside an
include, the name of the included file is returned.
<?php
// Displays the absolute path of this file
echo "The full path of this file is: " . __FILE__;
?>
__DIR__
The __DIR__ constant returns the directory of the file. If used inside an include, the directory of the included file
is returned. Here's an example:
<?php
// Displays the directory of this file
echo "The directory of this file is: " . __DIR__;
?>
__FUNCTION__
7
<?php
function myFunction(){
echo "The function name is - " . __FUNCTION__;
}
myFunction(); // Displays: The function name is - myFunction
?>
__CLASS__
The __CLASS__ constant returns the name of the current class. Here's an example:
<?php
class MyClass
{
public function getClassName(){
return __CLASS__;
}
}
$obj = new MyClass();
echo $obj->getClassName(); // Displays: MyClass
?>
__METHOD__
The __METHOD__ constant returns the name of the current class method.
<?php
class Sample
{
public function myMethod(){
echo __METHOD__;
}
}
$obj = new Sample();
$obj->myMethod(); // Displays: Sample::myMethod
?>
__NAMESPACE__
<?php
namespace MyNamespace;
class MyClass
{
public function getNamespace(){
return __NAMESPACE__; }
}
$obj = new MyClass();
echo $obj->getNamespace(); // Displays: MyNamespace
?>
8
The PHP echo Statement
The echo statement can output one or more strings. In general terms, the echo statement can display anything that
can be displayed to the browser, such as string, numbers, variables values, the results of expressions etc.
Since echo is a language construct not actually a function (like if statement), you can use it without parentheses
e.g. echo or echo(). However, if you want to pass more than one parameter to echo, the parameters must not
be enclosed within parentheses.
The following example will show you how to display a string of text with the echo statement:
<?php
// Displaying string of text
echo "Hello World!";
?>
The output of the above PHP code will look something like this:
Hello World!
The following example will show you how to display HTML code using the echo statement:
<?php
// Displaying HTML code
echo "<h4>This is a simple heading.</h4>";
echo "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The output of the above PHP code will look something like this:
Display Variables
The following example will show you how to display variable using the echo statement:
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
echo $txt;
echo "<br>";
9
echo $num;
echo "<br>";
echo $colors[0];
?>
The output of the above PHP code will look something like this:
Hello World!
123456789
Red
You can also use the print statement (an alternative to echo) to display output to the browser. Like echo the print
is also a language construct not a real function. So you can also use it without parentheses like: print or
print().
Both echo and print statement works exactly the same way except that the print statement can only output
one string, and always returns 1. That's why the echo statement considered marginally faster than the print
statement since it doesn't return any value.
The following example will show you how to display a string of text with the print statement:
<?php
// Displaying string of text
print "Hello World!";
?>
The output of the above PHP code will look something like this:
Hello World!
The following example will show you how to display HTML code using the print statement:
<?php
// Displaying HTML code
print "<h4>This is a simple heading.</h4>";
print "<h4 style='color: red;'>This is heading with style.</h4>";
?>
The output of the above PHP code will look something like this:
10
This is a simple heading.
This is heading with style.
Display Variables
The following example will show you how to display variable using the print statement:
<?php
// Defining variables
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
// Displaying variables
print $txt;
print "<br>";
print $num;
print "<br>";
print $colors[0];
?>
The output of the above PHP code will look something like this:
Hello World!
123456789
Red
The values assigned to a PHP variable may be of different data types including simple string and numeric types to
more complex data types like arrays and objects.
PHP supports total eight primitive data types: Integer, Floating point number or Float, String, Booleans, Array,
Object, resource and NULL. These data types are used to construct variables. Now let's discuss each one of them
in detail.
PHP Integers
Integers are whole numbers, without a decimal point (..., -2, -1, 0, 1, 2, ...). Integers can be specified in decimal
(base 10), hexadecimal (base 16 - prefixed with 0x) or octal (base 8 - prefixed with 0) notation, optionally
preceded by a sign (- or +).
<?php
$a = 123; // decimal number
var_dump($a);
echo "<br>";
$b = -123; // a negative number
var_dump($b);
11
echo "<br>";
$c = 0x1A; // hexadecimal number
var_dump($c);
echo "<br>";
$d = 0123; // octal number
var_dump($d);
?>
Note: Since PHP 5.4+ you can also specify integers in binary (base 2) notation. To use binary notation precede
the number with 0b (e.g. $var = 0b11111111;).
PHP Strings
Strings are sequences of characters, where every character is the same as a byte.
A string can hold letters, numbers, and special characters and it can be as large as up to 2GB (2147483647 bytes
maximum). The simplest way to specify a string is to enclose it in single quotes (e.g. 'Hello world!'), however you
can also use double quotes ("Hello world!").
<?php
$a = 'Hello world!';
echo $a;
echo "<br>";
$b = "Hello world!";
echo $b;
echo "<br>";
$c = 'Stay here, I\'ll be back.';
echo $c;
?>
Floating point numbers (also known as "floats", "doubles", or "real numbers") are decimal or fractional numbers,
like demonstrated in the example below.
<?php
$a = 1.234;
var_dump($a);
echo "<br>";
$b = 10.2e3;
var_dump($b);
echo "<br>";
$c = 4E-10;
var_dump($c);
?>
PHP Booleans
Booleans are like a switch it has only two possible values either 1 (true) or 0 (false).
12
<?php
// Assign the value TRUE to a variable
$show_error = true;
var_dump($show_error);
?>
PHP Arrays
An array is a variable that can hold more than one value at a time. It is useful to aggregate a series of related items
together, for example a set of country or city names.
An array is formally defined as an indexed collection of data values. Each index (also known as the key) of an
array is unique and references a corresponding value.
<?php
$colors = array("Red", "Green", "Blue");
var_dump($colors);
echo "<br>";
$color_codes = array(
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff"
);
var_dump($color_codes);
?>
PHP Objects
An object is a data type that not only allows storing data but also information on, how to process that data. An
object is a specific instance of a class which serve as templates for objects. Objects are created based on this
template via the new keyword.
Every object has properties and methods corresponding to those of its parent class. Every object instance is
completely independent, with its own properties and methods, and can thus be manipulated independently of other
objects of the same class.
Here's a simple example of a class definition followed by the object creation.
<?php
// Class definition
class greeting{
// properties
public $str = "Hello World!";
// methods
function show_greeting(){
return $this->str;
}
}
13
// Create object from class
$message = new greeting;
var_dump($message);
?>
Tip: The data elements stored within an object are referred to as its properties and the information, or code which
describing how to process the data is called the methods of the object.
PHP NULL
The special NULL value is used to represent empty variables in PHP. A variable of type NULL is a variable
without any data. NULL is the only possible value of type null.
<?php
$a = NULL;
var_dump($a);
echo "<br>";
$b = "Hello World!";
$b = NULL;
var_dump($b);
?>
When a variable is created without a value in PHP like $var; it is automatically assigned a value of null. Many
novice PHP developers mistakenly considered both $var1 = NULL; and $var2 = ""; are same, but this is
not true. Both variables are different — the $var1 has null value while $var2 indicates no value assigned to it.
PHP Resources
<?php
// Open a file for reading
$handle = fopen("note.txt", "r");
var_dump($handle);
echo "<br>";
PHP Strings
What is String in PHP?
A string is a sequence of letters, numbers, special characters and arithmetic values or combination of all. The
simplest way to create a string is to enclose the string literal (i.e. string characters) in single quotation marks ('),
like this:
14
$my_string = 'Hello World';
You can also use double quotation marks ("). However, single and double quotation marks work in different
ways. Strings enclosed in single-quotes are treated almost literally, whereas the string delimited by the double
quotes replaces variables with the string representations of their values as well as specially interpreting certain
escape sequences.
The escape-sequence replacements are:
Here's an example to clarify the differences between single and double quoted strings:
<?php
$my_str = 'World';
echo "Hello, $my_str!<br>"; // Displays: Hello World!
echo 'Hello, $my_str!<br>'; // Displays: Hello, $my_str!
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.
The strlen() function is used to calculate the number of characters inside a string. It also includes the blank
spaces inside the string.
<?php
$my_str = 'Welcome to Bahir Dar';
// Outputs: 28
echo strlen($my_str);
?>
15
<?php
$my_str = 'The quick brown fox jumps over the lazy dog.';
// Outputs: 9
echo str_word_count($my_str);
?>
The str_replace() replaces all occurrences of the search text within the target string.
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
If the truth does not fit the theory, change the truth.
You can optionally pass the fourth argument to the str_replace() function to know how many times the
string replacements was performed, like this.
<?php
$my_str = 'If the facts do not fit the theory, change the facts.';
Reversing a String
<?php
$my_str = 'You can do anything, but not everything.';
// Display reversed string
echo strrev($my_str);
?>
16
The output of the above code will be: .gnihtyreve ton tub ,gnihtyna od nac uoY
PHP Operators
You will learn how to manipulate or perform the operations on variables and values using 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 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:
The following example will show you these arithmetic operators in action:
<?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
?>
17
/= Divide and assign quotient $x /= $y $x = $x / $y
%= Divide and assign modulus $x %= $y $x = $x % $y
The following example will show you these assignment operators in action:
<?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
?>
The comparison operators are used to compare two values in a Boolean fashion.
The following example will show you these comparison operators in action:
<?php
$x = 25;
$y = 35;
$z = "25";
18
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
?>
The following example will show you these increment and decrement operators in action:
<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>
19
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
The following example will show you these logical operators in action:
<?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{
echo "$year is not a leap year.";
}
?>
There are two operators which are specifically designed for strings.
The following example will show you these string operators in action:
<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!
$x .= $y;
echo $x; // Outputs: Hello World!
?>
20
identity
The following example will show you these array operators in action:
<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>
PHP 7 introduces a new spaceship operator (<=>) which can be used for comparing two expressions. It is also
known as combined comparison operator.
The spaceship operator returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater. It
basically provides three-way comparison as shown in the following table:
The following example will show you how spaceship operator actually works:
<?php
// Comparing Integers
echo 1 <=> 1; // Outputs: 0
echo 1 <=> 2; // Outputs: -1
echo 2 <=> 1; // Outputs: 1
// Comparing Floats
echo 1.5 <=> 1.5; // Outputs: 0
echo 1.5 <=> 2.5; // Outputs: -1
echo 2.5 <=> 1.5; // Outputs: 1
// Comparing Strings
echo "x" <=> "x"; // Outputs: 0
echo "x" <=> "y"; // Outputs: -1
echo "y" <=> "x"; // Outputs: 1
?>
21
PHP If…Else Statements
PHP Conditional Statements
Like most programming languages, PHP also allows you to write code that perform different actions based on the
results of a logical or comparative test conditions at run time. This means, you can create test conditions in the
form of expressions that evaluates to either true or false and based on these results you can perform certain
actions.
There are several statements in PHP that you can use to make decisions:
The if statement
The if...else statement
The if...elseif....else statement
The switch...case statement
The if Statement
The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the
simplest PHP's conditional statements and can be written like:
if(condition){
// Code to be executed
}
The following example will output "Have a nice weekend!" if the current day is Friday:
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
You can enhance the decision making process by providing an alternative choice through adding an else statement
to the if statement. The if...else statement allows you to execute one block of code if the specified condition is
evaluates to true and another block of code if it is evaluates to false. It can be written, like this:
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
The following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output
"Have a nice day!"
22
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
The if...elseif...else a special statement that is used to combine multiple if...else statements.
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
The following example will output "Have a nice weekend!" if the current day is Friday, and "Have a nice
Sunday!" if the current day is Sunday, otherwise it will output "Have a nice day!"
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
The ternary operator provides a shorthand way of writing the if...else statements. The ternary operator is
represented by the question mark (?) symbol and it takes three operands: a condition to check, a result for true,
and a result for false.
To understand how this operator works, consider the following examples:
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>
23
Using the ternary operator the same code could be written in a more compact way:
The ternary operator in the example above selects the value on the left of the colon (i.e. 'Child') if the condition
evaluates to true (i.e. if $age is less than 18), and selects the value on the right of the colon (i.e. 'Adult') if the
condition evaluates to false.
Tip: Code written using the ternary operator can be hard to read. However, it provides a great way to write
compact if-else statements.
PHP 7 introduces a new null coalescing operator (??) which you can use as a shorthand where you need to use a
ternary operator in conjunction with isset() function.
To uderstand this in a better way consider the following line of code. It fetches the value of $_GET['name'], if
it does not exist or NULL, it returns 'anonymous'.
<?php
$name = isset($_GET['name']) ? $_GET['name'] : 'anonymous';
?>
Using the null coalescing operator the same code could be written as:
<?php
$name = $_GET['name'] ?? 'anonymous';
?>
As you can see the later syntax is more compact and easy to write.
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The
switch-case statement tests a variable against a series of values until it finds a match, and then executes the block
of code corresponding to that match.
switch(n){
case label1:
// Code to be executed if n=label1
break;
case label2:
// Code to be executed if n=label2
break;
...
default:
// Code to be executed if n is different from all labels
}
24
Consider the following example, which display a different message for each day.
<?php
$today = date("D");
switch($today){
case "Mon":
echo "Today is Monday. Clean your house.";
break;
case "Tue":
echo "Today is Tuesday. Buy some food.";
break;
case "Wed":
echo "Today is Wednesday. Visit a doctor.";
break;
case "Thu":
echo "Today is Thursday. Repair your car.";
break;
case "Fri":
echo "Today is Friday. Party tonight.";
break;
case "Sat":
echo "Today is Saturday. Its movie time.";
break;
case "Sun":
echo "Today is Sunday. Do some rest.";
break;
default:
echo "No information available for that day.";
break;
}
?>
The switch-case statement differs from the if-elseif-else statement in one important way. The
switch statement executes line by line (i.e. statement by statement) and once PHP finds a case statement that
evaluates to true, it's not only executes the code corresponding to that case statement, but also executes all the
subsequent case statements till the end of the switch block automatically.
To prevent this add a break statement to the end of each case block. The break statement tells PHP to break
out of the switch-case statement block once it executes the code associated with the first true case.
PHP Loops
Different Types of Loops in PHP
Loops are used to execute the same block of code again and again, until a certain condition is met. The basic idea
behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four
different types of loops.
while — loops through a block of code until the condition is evaluate to true.
do…while — the block of code executed once and then condition is evaluated. If the condition is true
the statement is repeated as long as the specified condition is true.
for — loops through a block of code until the counter reaches a specified number.
25
foreach — loops through a block of code for each element in an array.
You will also learn how to loop through the values of array using foreach() loop at the end of this chapter.
The foreach() loop work specifically with arrays.
The while statement will loops through a block of code until the condition in the while statement evaluate to
true.
while(condition){
// Code to be executed
}
The example below define a loop that starts with $i=1. The loop will continue to run as long as $i is less than or
equal to 3. The $i will increase by 1 each time the loop runs:
<?php
$i = 1;
while($i <= 3){
$i++;
echo "The number is " . $i . "<br>";
}
?>
The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration.
With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is
true, the statement is repeated as long as the specified condition evaluated to is true.
do{
// Code to be executed
}
while(condition);
The following example define a loop that starts with $i=1. It will then increase $i with 1, and print the output.
Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 3.
<?php
$i = 1;
do{
$i++;
echo "The number is " . $i . "<br>";
}
while($i <= 3);
?>
26
Difference Between while and do…while Loop
The while loop differs from the do-while loop in one important way — with a while loop, the condition to
be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false,
the loop will never be executed.
With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional
expression is false, because the condition is evaluated at the end of the loop iteration rather than the beginning.
The for loop repeats a block of code until a certain condition is met. It is typically used to execute a block of
code for certain number of times.
initialization — it is used to initialize the counter variables, and evaluated once unconditionally
before the first execution of the body of the loop.
condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true, the
loop continues and the nested statements are executed. If it evaluates to false, the execution of the
loop ends.
increment — it updates the loop counter with a new value. It is evaluate at the end of each iteration.
The example below defines a loop that starts with $i=1. The loop will continued until $i is less than, or equal to
5. The variable $i will increase by 1 each time the loop runs:
<?php
for($i=1; $i<=3; $i++){
echo "The number is " . $i . "<br>";
}
?>
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");
27
// Loop through colors array
foreach($colors as $value){
echo $value . "<br>";
}
?>
There is one more syntax of foreach loop, which is extension of the first.
<?php
$superhero = array("name" => "Peter Parker",
"email" => "[email protected]","age" => 18);
28
PHP Arrays
Arrays are complex variables that allow us to store more than one value or a group of values under a single
variable name. Let's suppose you want to store colors in your PHP script. Storing the colors one by one in a
variable could look something like this:
<?php
$color1 = "Red";
$color2 = "Green";
$color3 = "Blue";
?>
But what, if you want to store the states or city names of a country in variables and this time this not just three
may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable. And here
array comes into play.
There are three types of arrays that you can create. These are:
Indexed Arrays
An indexed or numeric array stores each array element with a numeric index. The following examples shows two
ways of creating an indexed array, the easiest way is:
<?php
// Define an indexed array
$colors = array("Red", "Green", "Blue");
?>
Note: In an indexed or numeric array, the indexes are automatically assigned and start with 0, and the values can
be any data type.
This is equivalent to the following example, in which indexes are assigned manually:
<?php
$colors[0] = "Red";
$colors[1] = "Green";
$colors[2] = "Blue";
?>
Associative Arrays
In an associative array, the keys assigned to values can be arbitrary and user defined strings. In the following
example the array uses keys instead of index numbers:
29
<?php
// Define an associative array
$ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>
The following example is equivalent to the previous example, but shows a different way of creating associative
arrays:
<?php
$ages["Peter"] = "22";
$ages["Clark"] = "32";
$ages["John"] = "28";
?>
Multidimensional Arrays
The multidimensional array is an array in which each element can also be an array and each element in the sub-
array can be an array or further contain array within itself and so on. An example of a multidimensional array will
look something like this:
<?php
// Define a multidimensional array
$contacts = array(
array(
"name" => "Peter Parker",
"email" => "[email protected]",
),
array(
"name" => "Clark Kent",
"email" => "[email protected]",
),
array(
"name" => "Harry Potter",
"email" => "[email protected]",
)
);
// Access nested value
echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>
You can see the structure and values of any array by using one of two statements — var_dump() or
print_r(). The print_r() statement, however, gives somewhat less information. Consider the following
example:
<?php
// Define array
$cities = array("London", "Paris", "New York");
30
// Display the cities array
print_r($cities);
?>
Array ( [0] => London [1] => Paris [2] => New York )
This output shows the key and the value for each element in the array. To get more information, use the following
statement:
<?php
// Define array
$cities = array("London", "Paris", "New York");
array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }
In the previous chapter you've learnt the essentials of PHP arrays i.e. what arrays are, how to create them, how to
view their structure, how to access their elements etc. You can do even more things with arrays like sorting the
elements in any order you like.
PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways
like alphabetically or numerically in ascending or descending order. Here we'll explore some of these functions
most commonly used for sorting arrays.
The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for
letters and numerically for numbers).
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
// Sorting and printing array
sort($colors);
print_r($colors);
?>
31
This print_r() statement gives the following output:
Array ( [0] => Blue [1] => Green [2] => Red [3] => Yellow )
Similarly you can sort the numeric elements of the array in ascending order.
<?php
// Define array
$numbers = array(1, 2, 2.5, 4, 7, 10);
Array ( [0] => 1 [1] => 2 [2] => 2.5 [3] => 4 [4] => 7 [5] => 10 )
The rsort() function is used for sorting the elements of the indexed array in descending order (alphabetically
for letters and numerically for numbers).
<?php
// Define array
$colors = array("Red", "Green", "Blue", "Yellow");
Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
Similarly you can sort the numeric elements of the array in descending order.
<?php
// Define array
$numbers = array(1, 2, 2.5, 4, 7, 10);
32
Array ( [0] => 10 [1] => 7 [2] => 4 [3] => 2.5 [4] => 2 [5] => 1 )
The asort() function sorts the elements of an associative array in ascending order according to the value. It
works just like sort(), but it preserves the association between keys and its values while sorting.
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
The arsort() function sorts the elements of an associative array in descending order according to the value. It
works just like rsort(), but it preserves the association between keys and its values while sorting.
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
The ksort() function sorts the elements of an associative array in ascending order by their keys. It preserves
the association between keys and its values while sorting, same as asort() function.
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
33
print_r($age);
?>
The krsort() function sorts the elements of an associative array in descending order by their keys. It preserves
the association between keys and its values while sorting, same as arsort() function.
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
34
PHP Functions
PHP Built-in Functions
Please check out PHP reference section for a complete list of useful PHP built-in functions.
In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create
reusable code packages that perform specific tasks and can be kept and maintained separately form main program.
Here are some advantages of using functions:
Functions reduce the repetition of code within a program — Function allows you to extract commonly
used block of code into a single component. Now you can perform the same task by calling this function
wherever you want within your script without having to copy and paste the same block of code again
and again.
Functions makes the code much easier to maintain — Since a function created once can be used many
times, so any changes made inside a function automatically implemented at all the places without
touching the several files.
Functions makes it easier to eliminate the errors — When the program is subdivided into functions, if
any error occur you know exactly what function causing the error and where to find it. Therefore, fixing
errors becomes much easier.
Functions can be reused in other application — Because a function is separated from the rest of the
script, it's easy to reuse the same function in other applications just by including the php file containing
those functions.
The following section will show you how easily you can define your own function in PHP.
function functionName(){
// Code to be executed
}
The declaration of a user-defined function start with the word function, followed by the name of the function
you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets
{}.
This is a simple example of an user-defined function, that display today's date:
<?php
// Defining function
35
function whatIsToday(){
echo("Today is ".date("d-m-y",time()));
//echo "Today is”.date('l', mktime());
}
// Calling function
whatIsToday();
?>
Note: A function name must start with a letter or underscore character not with a number, optionally followed by
the more letters, numbers, or underscore characters. Function names are case-insensitive.
You can specify parameters when you define your function to accept input values at run time. The parameters
work like placeholder variables within a function; they're replaced at run time by the values (known as argument)
provided to the function at the time of invocation.
You can define as many parameters as you like. However for each parameter you specify, a corresponding
argument needs to be passed to the function when it is called.
The getSum() function in following example takes two integer values as arguments, simply add them together
and then display the result in the browser.
<?php
// Defining function
function getSum($num1, $num2){
$sum = $num1 + $num2;
echo "Sum of the two numbers $num1 and $num2 is : $sum";
}
// Calling function
getSum(10, 20);
?>
Tip: An argument is a value that you pass to a function, and a parameter is the variable within the function that
receives the argument. However, in common usage these terms are interchangeable i.e. an argument is a
parameter is an argument.
You can also create functions with optional parameters — just insert the parameter name, followed by an equals
(=) sign, followed by a default value, like this.
36
<?php
// Defining function
function customFont($font, $size=1.5){
echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello,
world!</p>";
}
// Calling function
customFont("Arial", 2);
customFont("Times", 3);
customFont("Courier");
?>
As you can see the third call to customFont() doesn't include the second argument. This causes PHP engine to
use the default value for the $size parameter which is 1.5.
A function can return a value back to the script that called the function using the return statement. The value may
be of any type, including arrays and objects.
<?php
// Defining function
function getSum($num1, $num2){
$total = $num1 + $num2;
return $total;
}
A function cannot return multiple values. However, you can obtain similar results by returning an array, as
demonstrated in the following example.
<?php
// Defining function
function divideNumbers($dividend, $divisor){
$quotient = $dividend / $divisor;
$array = array($dividend, $divisor, $quotient);
return $array;
}
37
Passing Arguments to a Function by Reference
In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function
arguments are passed by value so that if the value of the argument within the function is changed, it does not get
affected outside of the function. However, to allow a function to modify its arguments, they must be passed by
reference.
Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function
definition, as shown in the example below:
<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}
$mynum = 5;
echo $mynum; // Outputs: 5
selfMultiply($mynum);
echo $mynum; // Outputs: 25
?>
However, you can declare the variables anywhere in a PHP script. But, the location of the declaration determines
the extent of a variable's visibility within the PHP program i.e. where the variable can be used or accessed. This
accessibility is known as variable scope.
By default, variables declared within a function are local and they cannot be viewed or manipulated from outside
of that function, as demonstrated in the example below:
<?php
// Defining function
function test(){
$greet = "Hello World!";
echo $greet;
}
Similarly, if you try to access or import an outside variable inside the function, you'll get an undefined variable
error, as shown in the following example:
<?php
$greet = "Hello World!";
// Defining function
38
function test(){
echo $greet;
}
As you can see in the above examples the variable declared inside the function is not accessible from outside,
likewise the variable declared outside of the function is not accessible inside of the function. This separation
reduces the chances of variables within a function getting affected by the variables in the main program.
Tip: It is possible to reuse the same name for a variable in different functions, since local variables are only
recognized by the function in which they are declared.
There may be a situation when you need to import a variable from the main program into a function, or vice versa.
In such cases, you can use the global keyword before the variables inside a function. This keyword turns the
variable into a global variable, making it visible or accessible both inside and outside the function, as show in the
example below:
<?php
$greet = "Hello World!";
// Defining function
function test(){
global $greet;
echo $greet;
}
A recursive function is a function that calls itself again and again until a condition is satisfied. Recursive functions
are often used to solve complex mathematical calculations, or to process deeply nested structures e.g., printing all
the elements of a deeply nested array.
The following example demonstrates how a recursive function works.
<?php
// Defining recursive function
function printValues($arr) {
39
global $count;
global $items;
/*
Loop through array, if value is itself an array recursively call the
function else add the value found to the output items array,
and increment counter by 1 for each value found
*/
foreach($arr as $a){
if(is_array($a)){
printValues($a);
} else{
$items[] = $a;
$count++;
}
}
40
"Dinosaur" => array(
"T-rex",
"Alamosaurus"
)));
Note: Be careful while creating recursive functions, because if code is written improperly it may result in an
infinite loop of function calling.
41
PHP Classes and Objects
Object-Oriented Programming (OOP) is a programming model that is based on the concept of classes
and objects. As opposed to procedural programming where the focus is on writing procedures or
functions that perform operations on the data, in object-oriented programming the focus is on the
creations of objects which contain both data and functions together.
Object-oriented programming has several advantages over conventional or procedural style of
programming. The most important ones are listed below:
The following sections will describe how classes and objects work in PHP.
Tip: The idea behind Don't Repeat Yourself (DRY) principle is reducing the repetition of code by
abstracting out the code that are common for the application and placing them at a single place and reuse
them instead of repeating it.
Classes and objects are the two main aspects of object-oriented programming. A class is a self-
contained, independent collection of variables and functions which work together to perform one or
more specific tasks, while objects are individual instances of a class.
A class acts as a template or blueprint from which lots of individual objects can be created. When
individual objects are created, they inherit the same generic properties and behaviors, although each
object may have different values for certain properties.
For example, think of a class as a blueprint for a house. The blueprint itself is not a house, but is a
detailed plan of the house. While, an object is like an actual house built according to that blueprint. We
can build several identical houses from the same blueprint, but each house may have different paints,
interiors and families inside, as shown in the illustration below.
42
A class can be declared using the class keyword, followed by the name of the class and a pair of curly
braces ({}), as shown in the following example.
Let's create a PHP file named Rectangle.php and put the following example code inside it so that our
class code should be separated from rest of the program. We can then use it wherever it's needed by
simply including the Rectangle.php file.
<?php
class Rectangle
{
// Declare properties
public $length = 0;
public $width = 0;
The public keyword before the properties and methods in the example above, is an access modifier,
which indicates that this property or method is accessible from anywhere. We will learn more about this
a little later in this chapter.
Note: Syntactically, variables within a class are called properties, whereas functions are called methods.
Also class names conventionally are written in PascalCase i.e. each concatenated word starts with an
uppercase letter (e.g. MyClass).
Once a class has been defined, objects can be created from the class with the new keyword. Class
methods and properties can directly be accessed through this object instance.
Create another PHP file name test.php and put the following code inside it.
<?php
// Include class definition
require "Rectangle.php";
43
$obj = new Rectangle;
The arrow symbol (->) is an OOP construct that is used to access contained properties and methods of a
given object. Whereas, the pseudo-variable $this provides a reference to the calling object i.e. the
object to which the method belongs.
The real power of object oriented programming becomes evident when using multiple instances of the
same class, as shown in the following example:
<?php
// Include class definition
require "Rectangle.php";
As you can see in the above example, calling the getArea() method on different objects causes that
method to operate on a different set of data. Each object instance is completely independent, with its
44
own properties and methods, and thus can be manipulated independently, even if they're of the same
class.
To make the object-oriented programming easier, PHP provides some magic methods that are executed
automatically when certain actions occur within an object.
For example, the magic method __construct() (known as constructor) is executed automatically
whenever a new object is created. Similarly, the magic method __destruct() (known as destructor) is
executed automatically when the object is destroyed. A destructor function cleans up any resources
allocated to an object once the object is destroyed.
<?php
class MyClass
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
// Destructor
public function __destruct(){
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}
The PHP code in the above example will produce the following output:
A destructor is called automatically when a scripts ends. However, to explicitly trigger the destructor,
you can destroy the object using the PHP unset() function, as follow:
<?php
class MyClass
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
// Destructor
public function __destruct(){
45
echo 'The class "' . __CLASS__ . '" was destroyed.<br>';
}
}
Now, the PHP code in the above example will produce the following output:
Tip: PHP automatically clean up all resources allocated during execution when the script is finished,
e.g. closing database connections, destroying objects, etc.
Note: The __CLASS__ is a magic constant which contains the name of the class in which it is occur. It is
empty, if it occurs outside of the class.
Classes can inherit the properties and methods of another class using the extends keyword. This process
of extensibility is called inheritance. It is probably the most powerful reason behind using the object-
oriented programming model.
<?php
// Include class definition
require "Rectangle.php";
46
$obj->width = 20;
The PHP code in the above example will produce the following output:
As you can see in the above example, even though the class definition of Square doesn't explicitly
contain getArea() method nor the $length and $width property, instances of the Square class can use
them, as they inherited from the parent Rectangle class.
Tip: Since a child class is derived from a parent class, it is also referred to as a derived class, and its
parent is called the base class.
When working with classes, you can even restrict access to its properties and methods using the
visibility keywords for greater control. There are three visibility keywords (from most visible to least
visible): public, protected, private, which determines how and from where properties and methods
can be accessed and modified.
public — A public property or method can be accessed anywhere, from within the class and outside.
This is the default visibility for all class members in PHP.
protected — A protected property or method can only be accessed from within the class itself or in child
or inherited classes i.e. classes that extends that class.
private — A private property or method is accessible only from within the class that defines it. Even
child or inherited classes cannot access private properties or methods.
The following example will show you how this visibility actually works:
<?php
// Class definition
class Automobile
{
// Declare properties
public $fuel;
protected $engine;
private $transmission;
}
class Car extends Automobile
{
// Constructor
public function __construct(){
echo 'The class "' . __CLASS__ . '" was initiated!<br>';
}
47
}
In addition to the visibility, properties and methods can also be declared as static, which makes them
accessible without needing an instantiation of the class. Static properties and methods can be accessed
using the scope resolution operator (::), like this: ClassName::$property and ClassName::method().
A property declared as static cannot be accessed via the object of that class though a static method can
be, as demonstrated in the following example:
<?php
// Class definition
class HelloClass
{
// Declare a static property
public static $greeting = "Hello World!";
The keyword self in the above example means "the current class". It is never preceded by a dollar sign
($) and always followed by the :: operator (e.g. self::$name).
48
The self keyword is different from the this keyword which means "the current object" or "the current
instance of a class". The this keyword is always preceded by a dollar sign ($) and followed by the ->
operator (e.g. $this->name).
Note: Since static methods can be called without an instance of a class (i.e. object), the pseudo-variable
$this is not available inside the method declared as static.
We hope you've understood the basic concepts of object-oriented programming by now. You'll find
more examples on OOP in PHP and MySQL database section.
What is an Exception
An exception is a signal that indicates some sort of exceptional event or error has occurred. Exceptions
can be caused due to various reasons, for example, database connection or query fails, file that you're
trying to access doesn't exist, and so on.
PHP provides a powerful exception handling mechanism that allows you to handle exceptions in a
graceful way. As opposed to PHP's traditional error-handling system, exception handling is the object-
oriented method for handling errors, which provides more controlled and flexible form of error
reporting. Exception model was first introduced in PHP 5.
In exception-based approach, program code is written in a try block, an exception can be thrown using
the throw statement when an exceptional event occurs during the execution of code in a try block. It is
then caught and resolved by one or more catch blocks.
The following example demonstrates how exception handling works:
<?php
function division($dividend, $divisor){
// Throw exception if divisor is zero
if($divisor == 0){
throw new Exception('Division by zero.');
} else{
$quotient = $dividend / $divisor;
echo "<p>$dividend / $divisor = $quotient</p>";
}
}
try{
division(10, 2);
division(30, -4);
division(15, 0);
49
// Handle the exception
echo "<p>Caught exception: " . $e->getMessage() . "</p>";
}
// Continue execution
echo "<p>Hello World!</p>";
?>
You might be wondering what this code was all about. Well, let's go through each part of this code one
by one for a better understanding.
Explanation of Code
The PHP's exception handling system has basically four parts: try, throw, catch, and the Exception
class. The following list describes how each part exactly works.
The division() function in the example above checks if a divisor is equal to zero. If it is, an exception
is thrown via PHP's throw statement. Otherwise this function perform the division using given numbers
and display the result.
Later, the division() function is called within a try block with different arguments. If an exception is
generated while executing the code within the try block, PHP stops execution at that point and attempt
to find the corresponding catch block. If it is found, the code within that catch block is executed, if
not, a fatal error is generated.
The catch block typically catch the exception thrown within the try block and creates an object ($e)
containing the exception information. The error message from this object can be retrieved using the
Exception's getMessage() method.
The PHP's Exception class also provides getCode(), getFile(), getLine() and getTraceAsString()
methods that can be used to generate detailed debugging information.
<?php
// Turn off default error reporting
error_reporting(0);
try{
$file = "somefile.txt";
50
// Display file contents
echo $content;
} catch(Exception $e){
echo "<h3>Caught Exception!</h3>";
echo "<p>Error message: " . $e->getMessage() . "</p>";
echo "<p>File: " . $e->getFile() . "</p>";
echo "<p>Line: " . $e->getLine() . "</p>";
echo "<p>Error code: " . $e->getCode() . "</p>";
echo "<p>Trace: " . $e->getTraceAsString() . "</p>";
}
?>
The Exception's constructor optionally takes an exception message and an exception code. While the
exception message is typically used to display generic information on what went wrong, the exception
code can be used to categorize the errors. The exception code provided can be retrieved later via
Exception's getCode() method.
Tip: Exception should only be used to denote exceptional conditions; they should not be used to control
normal application flow e.g., jump to another place in the script at a particular point. Doing that would
adversely affect your application's performance.
You can even define your own custom exception handlers to treat different types of exceptions in a
different way. It allows you to use a separate catch block for each exception type.
You can define a custom exception by extending the Exception class, because Exception is the base
class for all exceptions. The custom exception class inherits all the properties and methods from PHP's
Exception class. You can also add your custom methods to the custom exception class. Let's check out
the following example:
<?php
// Extending the Exception class
class EmptyEmailException extends Exception {}
class InvalidEmailException extends Exception {}
$email = "[email protected]";
try{
// Throw exception if email is empty
if($email == ""){
throw new EmptyEmailException("<p>Please enter your E-mail address!</p>");
}
51
} catch(InvalidEmailException $e){
echo $e->getMessage();
}
?>
In the above example we've derived two new exception classes: EmptyEmailException, and
InvalidEmailException from the Exception base class. Multiple catch blocks are used to display
different error messages, depending on the type of exception generated.
Since these custom exception classes inherits the properties and methods from the Exception class, so
we can use the Exception's class methods like getMessage(), getLine(), getFile(), etc. to retrieve
error information from the exception object.
As we've discussed earlier in this chapter if an exception is not caught, PHP generates a Fatal Error with
an "Uncaught Exception ..." message. This error message may contain sensitive information like file
name and line number where the problem occurs. If you don't want to expose such information to the
user, you can create a custom function and register it with the set_exception_handler() function to
handle all uncaught exceptions.
<?php
function handleUncaughtException($e){
// Display generic error message to the user
echo "Opps! Something went wrong. Please try again, or contact us if the problem
persists.";
// Throw an exception
throw new Exception("Testing Exception!");
?>
Note: An uncaught exception will always result in script termination. So if you want the script to
continue executing beyond the point where the exception occurred, you must have at least one
corresponding catch block for each try block.
52