Module 4 18CS63
Module 4 18CS63
Module IV
Arrays, Classes & Objects, Exception Handling in PHP
PHP Arrays and Superglobals, Arrays, $_GET and $_POST Superglobal Arrays,
$_SERVER Array, $_Files Array, Reading/Writing Files, PHP Classes and Objects,
Object-Oriented Overview, Classes and Objects in PHP, Object Oriented Design,
Error Handling and Validation, What are Errors and Exceptions?, PHP Error
Reporting, PHP Error and Exception Handling
4.1 Arrays
PHP supports arrays, like most other programming languages. An array is a data structure that
allows the programmer to collect a number of related elements together in a single variable. In
PHP an array is an ordered map, which associates each value in the array with a key.
An array of key-value pair, containing the days of the week can be visualized as follows –
• Array keys in most programming languages are limited to integers, start at 0, and go up by
1. InPHP, keys can be either integers or strings.
• Array values are not restricted to integers and strings. They can be any object, type, or
primitive supported in PHP.
Eg -
$days = array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”);
Vinutha G K,Shwetha G N,Sunitha
Module IV – Arrays, Classes & Objects, Exception Handling in PHP
$days = [“Mon”,”Tue”,”Wed”,”Thu”,”Fri”]; // alternate syntax
$count=array(“one”,”two”,3,4);
$count = [“one”,”two”,3,4];
In these examples, because no keys are explicitly defined for the array, the default key values are
0, 1, 2, . . . , n.
The array elements can also be defined individually using the square bracket notation:
$days = array();
$days[0] = "Mon";
$days[1] = "Tue";
$days[2] = "Wed";
// also alternate approach
$daysB = array();
$daysB[] = "Mon";
$daysB[] = "Tue";
$daysB[] = "Wed";
• Arrays are dynamically sized - elements are added to or deleted from the array during run-
time.Elements within an array are accessed using the familiar square bracket notation.
Arrayvariable[index];
The code below echoes the value of our $days array for the key=1, which results in
output of Tue.
echo "Value at index 1 is ". $days[1]; // index starts at zero
• In PHP, keys can be explicitly defined along with the values. This allows us to use keys
otherthan the classic 0, 1, 2, . . . , n to define the indexes of an array. The array
$days = array(“Mon”,”Tue”,”Wed”,”Thu”,”Fri”); can be defined more explicitly by specifying
the keys and values as
$days = array(0 => "Mon", 1 => "Tue", 2 => "Wed", 3 => "Thu", 4=> "Fri");
Where 0,1,2,… are the keys and “Mon”,”Tue”,… are the values.
These types of arrays in PHP are generally referred to as associative arrays. Keys must be either
integer or string values, but the values can be any type of PHP data type, including other arrays.
In the above example, the keys are strings (for the weekdays) and the values are weather
forecasts for the specified day in integer degrees. To access an element in an associative array,
simply use the key value rather than an index:
echo $forecast["Wed"]; // this will output 52
• Multidimensional Arrays
PHP also supports multidimensional arrays, an array within another array. It can be defined as -
$month = array(
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri"),
array("Mon","Tue","Wed","Thu","Fri")
);
echo $month[0][3]; // outputs Thu
OR
$cart = array();
$cart[] = array("id" => 37, "title" => "Burial at Ornans", "quantity" => 1);
$cart[] = array("id" => 345, "title" => "The Death of Marat", "quantity" => 1);
$cart[] = array("id" => 63, "title" => "Starry Night", "quantity" => 1);
Program-1.Indexed array
There are two ways to create indexed arrays:
• The index can be assigned automatically (index always starts at 0), like this
$cars = array("Volvo", "BMW", "Toyota");
or
• the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Output: I like Volvo, BMW and Toyota.
Program2: Associative array
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
When there is nonsequential integer keys or strings as keys (i.e., an associative array), the
accessing of elements can’t be done using a $i, in such cases foreach loop is used. Foreach loop
iterates till the end of array and stops. Each value can be accessed during the iterations, or both
the key and value can be accessed, as shown below.
// while loop
$i=0;
while ($i < count($days)) {
echo $days[$i] . "<br>";
$i++;
}
// do while loop
$i=0;
do {
echo $days[$i] . "<br>";
$i++;
} while ($i < count($days));
// for loop
for ($i=0; $i<count($days); $i++) {
echo $days[$i] . "<br>";
}
As an alternative to specifying the index, a new element can be added to the end of any existing
array by -
$days[ ] = "Sun";
The advantage to this approach is that you don’t have to remember the last index key used.
$days = array("Mon","Tue","Wed","Thu","Fri");
$days[7] = "Sat";
print_r($days);
The print_r() - will display the non-NULL elements of the array, as shown below -
Array ([0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri [7] => Sat)
Elements can be deleted from the array explicitly by using the unset() function –
$days = array("Mon","Tue","Wed","Thu","Fri");
unset($days[2]);
unset($days[3]);
print_r($days); // outputs: Array ( [0] => Mon [1] => Tue [4] => Fri )
The Null values in arrays can be removed and array is reindexed by using the array_values()
function.
$b = array_values($days);
print_r($b); // outputs: Array ( [0] => Mon [1] => Tue [2] => Fri )
// Array is reindexed.
print_r($days) // outputs: Array ( [0] => Mon [1] => Tue [4] => Fri )
There are many built-in sort functions, which sort by key or by value in PHP.
• sort(arrayname); - sort the array in ascending order by its values. The array itself is sorted.
$days = array("Mon","Tue","Wed","Thu","Fri");
sort($days);
print_r($days); // outputs: Array ([0] => Fri [1] => Mon [2] => Thu [3] => Tue [4] => Wed)
sort() function loses the association between the values and the keys.
• array_values($Arrayname): This method returns an indexed array with the values being the
values of $ Arrayname.
Eg: print_r(array_values($days))
Outputs - Array ( [0] => Mon [1] => Tue [2] => Wed [3] => Thu [4] => Fri )
Vinutha G K,Shwetha G N,Sunitha
Module IV – Arrays, Classes & Objects, Exception Handling in PHP
• array_rand($Arrayname, $num=1): This function returns an array of, as many random keys
as are requested. If you only want one, the key itself is returned;otherwise, an array of keys is
returned.
For example, print_r(array_rand($days,2))might output: Array (3, 0)
function doPrint($value,$key)
{
echo $key . ": " . $value . “<br />”;
}
Output:
0 : hello
1 : world
function doPrint($value,$key,$t1,$t2,$t3)
{
echo $key . ": " . $value .
“<br />”; echo “$t1 $t2 $t3
<br />”,
}
Output:
0 : hello
one two 3
Vinutha G K,Shwetha G N,Sunitha
Module IV – Arrays, Classes & Objects, Exception Handling in PHP
1 : world
one two 3
• in_array($value, $arrayname): This method search the array $ arrayname for a value
($value).It returns true if value is found, and false otherwise.
if(in_array(“Wed”,$days))
echo “Element found”;
else
echo “Element not found”;
Superglobal Arrays
PHP uses special predefined associative arrays called superglobal variables. It allows the
programmer to easily access HTTP headers, query string parameters, and other commonlyneeded
information. They are called superglobal because these arrays are always accessible, from a
function , class or file, without using the global keyword.
NAME DESCRIPTION
$GLOBALS Array for storing user data that needs superglobal scope
$_COOKIES Array of cookie data passed to page via HTTP request
$_ENV Array of server environment data
$_FILES Array of file items uploaded to the server
$_GET Array of query string data passed to the server via the URL
$_POST Array of query string data passed to the server via the HTTP header
$_REQUEST Array containing the contents of $_GET, $_POST, and $_COOKIES
$_SESSION Array that contains session data
$_SERVER Array containing information about the request and the server
An HTML form allows a client to send data to the server. That data is formatted such that each
value is associated with a name of control defined in the form. If the form was submitted using
an HTTP GET request ie. <form method=”get” action=”server file path” >, then the resulting
URL will contain the data in the query string.
Vinutha G K,Shwetha G N,Sunitha
Module IV – Arrays, Classes & Objects, Exception Handling in PHP
Eg-
https://name-processing.php?firstname=amith&lastname=kumar%20singh
retrieve the values sent through the URL using $_GET[“firstname”] and $_GET[“lastname”]
PHP will populate the superglobal $_GET array using the contents of this query string in the
URL.
If the form was sent using HTTP POST, then the values will be sent through HTTP POST
request body. The values and keys are stored in the $_POST array.
Thus the values passed by the user can easily be accessed at the server side using the global
arrays $_GET[] and $_POST[] for ‘get’ and ‘post’ methods respectively.
isset() function is used to check if any of the fields are set. It returns true if the value is sent
otherwise returns false.
isset($POST[‘name’]);
User.html Userpass.php
<html> <?php
<body> if ($_SERVER["REQUEST_METHOD"] ==
<h1>User Login Page</h1> "POST")
<form action="userpass.php" {
method="POST"> if ( isset($_POST["uname"]) &&
Name <input type="text" isset($_POST["pass"]) )
name="uname"/><br/> {
Pass <input type="password" echo "handling user login now ...";
name="pass"/><br/> $a=$_POST["uname"];
<input type="submit"> $b=$_POST["pass"];
</form> echo "username is $a <br /> password is
</body> $b";
</html> }
}
?>
Output:
Sometimes it is required to access multiple values associated with a single name from few
controls in form, like checkboxes.
A group of checkboxes will have the same name eg :(name="day"), and multiple values.
To overcome this limitation, change the HTML in the form, ie. change the name attribute for
each checkbox from day to day[].
<form method="get">
Please select days of the week you are free.<br />
Monday <input type="checkbox" name="day[ ]" value="Monday" /> <br />
Tuesday <input type="checkbox" name="day[ ]" value="Tuesday" /> <br />
Wednesday <input type="checkbox" name="day[ ]" value="Wednesday" /> <br />
Thursday <input type="checkbox" name="day[ ]" value="Thursday" /> <br />
Friday <input type="checkbox" name="day[ ]" value="Friday" /> <br />
<input type="submit" value="Submit">
</form>
After making this change in the HTML, the corresponding variable $_GET['day'] will now have
a value that is of type array. The values are accessed using the foreach loop and count() function
returns the length of the array.
<html>
<body>
<form action="" method="post">
<label>What Destination Would you Like to Go To?</label><br>
<input type="checkbox" name="Islands[]" value="Aruba- Aruba is a
beautiful desert island">Aruba<br>
<input type="checkbox" name="Islands[]" value="Hawaii- Hawaii is a
beautiful strand of islands located in the heart of the Pacific
Ocean.">Hawaii<br>
<input type="checkbox" name="Islands[]" value="Jamaica- Jamaica is a
beautiful island located in the Caribbean Sea">Jamaica<br>
<input type="submit" name="button" value="Submit"/></form>
</form>
</body>
</html>
<?php
$destinations= $_POST['Islands'];
if(isset($destinations)) {
echo 'You have chosen:' . '<br>' . '<br>';
foreach ($destinations as $key => $value)
Vinutha G K,Shwetha G N,Sunitha
Module IV – Arrays, Classes & Objects, Exception Handling in PHP
{
echo $value . '<br>';
}
}
else
{
echo "You haven't selected any destination";
}
?>
Output:
The developer must be able to handle the following cases for every query string or form value:
• Query string parameter doesn’t exist.
• Query string parameter doesn’t contain a value.
• Query string parameter value isn’t the correct type.
• Value is required for a database lookup, but provided value doesn’t exist in the database
table.
The $_SERVER array can be classified into keys containing information about the serversettings
and keys with request header information.
Eg: $_SERVER['SERVER_NAME'] ;
$_SERVER['DOCUMENT_ROOT']; etc.
• REQUEST_METHOD key returns the request method that was used to access the
page: GET,HEAD, POST, PUT.
• HTTP_USER_AGENT key returns the operating system and browser used by the client.
• HTTP_REFERER key returns the address of the page that referred (linked) us to
this page.Eg: $_SERVER['REQUEST_METHOD'] ;
$_SERVER['REMOTE_ADDR']; etc.
The below figure illustrates the process of uploading a file to the server and how the
corresponding upload information is contained in the $_FILES array.
• To restrict the filesize using HTML form, add a hidden input field before any other
input fields in your HTML form with a name of MAX_FILE_SIZE. This technique
allows php.ini (a file used for configuring PHP settings) maximum file size to be large,
while letting files with smaller size. The checking of file size is done at the server side.
• The more complete client-side mechanism to prevent a large file from uploading is to
prevalidatethe form using JavaScript.
<script>
var file = document.getElementById('file1');
var max_size = document.getElementById("max_file_size").value;
if (file.files && file.files.length ==1){
Vinutha G K,Shwetha G N,Sunitha Page 14
Module IV – Arrays, Classes & Objects, Exception Handling in PHP 18CS63
if (file.files[0].size > max_size) {
alert("The file must be less than " + (max_size/1024) +
"KB");e.preventDefault();
}
}
</script>
• The third mechanism for limiting the uploaded file size is to add a simple check on the server
side using PHP. This technique checks the file size on the server by simply checking the size
field in the $_FILES array.
$max_file_size = 10000000;
foreach($_FILES as $fileKey => $fileArray)
{
if ($fileArray["size"] > $max_file_size) {
echo "Error: " . $fileKey . " is too big";
}
printf("%s is %.2f KB", $fileKey, $fileArray["size"]/1024);
}
Program
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
Select File:
<input type="file" name="fileToUpload"/>
<input type="submit" />
</form>
</body>
</html>
<?php
$target_dir = "upload-images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
}
?>
Output:
Program
<?php
if(isset($_FILES['images']))
{
echo "<pre>";
print_r($_FILES);
echo "<pre>";
$file_name=$_FILES['images']['name'];
$file_size=$_FILES['images']['size'];
$file_tmp=$_FILES['images']['tmp_name'];
$file_type=$_FILES['images']['type'];
if(move_uploaded_file($file_tmp,"upload-images/".$file_name))
{
echo "Succesfully uploaded";
}
else
{
echo "couldnot uploded succesfully";
}}
?>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
Stream Access
The functions used in this technique are similar to that of C programming.
The function fopen() takes a file location or URL and access mode as parameters. The returned
value is a stream resource (file handle).
Some of the common modes are “r” for read, “w” for write, and “c” creates a new file for
writing, “rw” for read and write.
• Write a PHP script to retrieve the fields from the text file (EmpID, EmpName, Department).
Thefields are delimited by comma(,). Display the fields separately.
<?php
$filearr = file(“Emp.txt”);
Foreach($filearr as $empdata)
{
$EmpFields = explode(‘,’, $empdata);
$id= $EmpFields[0];
$name = $EmpFields[1];
$dept = $EmpFields[2];
Echo “ID of Employee is $id <br /> Name is $name <br /> Department is $dept<br />”;
}
In a server, there are thousands of users making requests at once, so objects are destroyed upon
responding to each request and also the memory is shared between many simultaneous requests.
It is possible to have objects persist between multiple requests in a server using serialization,
which rapidly stores and retrieves object .
The below figure shows the lifetimes of objects in memory between a desktop and a browser
application.
Defining Classes
The PHP syntax for defining a class uses the class keyword followed by the classname and { }
braces. The properties and methods of the class are defined within the braces.
Eg –
class Employee{
public $EmpName;
public $EmpID;
public $Dept;
public $Designation;
public $salary;
}
Each property in the class is declared using one of the keywords public, protected, or private
access specifiers followed by the property or variable name.
Instantiating Objects
Once a class has been defined, any number of instances of that class can be created, using the
new keyword.
To create two new instances of the Employee class called $emp1 and $emp2, you instantiate two
new objects using the new keyword as follows:
$emp1 = new Employee();
$emp2 = new Employee ();
Constructors
A constructor is a member function of a class which initializes objects of a class. Objects can be
done by using above method also, but if there are many objects then it is difficult to initialize.
In PHP, constructors are defined as functions with the name construct() (two underscores
before the word construct.).
class Employee{
public $EmpName;
public $EmpID;
public $Dept;
public $Designation;
public $salary;
function construct($name,$id,$dept,$desig,$sal)
{
$this->EmpName = $name;
$this->EmpID = $id;
$this->Dept = $dept;
$this-> Designation = $desig;
$this->salary = $sal;
}
}
In the constructor each parameter is assigned to an internal class variable using the $this->
syntax. Inside a class $this syntax must be used to reference all properties and methods
associated with this particular instance of a class.
The object is created as follows –
$emp1 = new Employee("Pablo","M123","Testing","Manager","35K");
$emp2 = new Employee ("Salvador","M124","Testing","Trainee",”10K”);
Methods
In object-oriented concept, the operations on properties of objects are performed within the
methods defined in a class. Methods are like functions, except they are associated with a class.
They define the tasks each instance of a class can perform and are useful since they associate
behavior with objects.
function __construct($n,$usn,$add,$avg)
{
$this->name = $n;
$this->USN= $usn;
$this->address = $add;
$this->avg = $avg;
}
function display()
{
echo "name is $this->name <br /> USN is
$this->USN <br />";
echo "Address is $this->address <br /> Avg is
$this->avg <br />";
}
}
Class Object
Student $s1:Student
+ name: String + name: Shwetha
+ USN: String + USN: 123
+ address: String + address: Bangalore
+ avg: float + avg: 66
+ construct(int, String, String, String) + construct(int, String, String, String)
+ display( ) : void + display( ) : void
_ _toString( ) method – Any function which returns a string, can be renamed as _ _toString( ).
The function is called by just using the object as a variable.
Eg-
$s1 = new Student( );
Echo $s1; //calls the _ _toString( ) function and displays the string returned.
Visibility
The visibility of a property or method determines the accessibility of a class member (i.e., a
property or method) and can be set to public, private, or protected.
In UML, the "+" symbol is used to denote public properties and methods, the "–" symbol for
private members, and the "#" symbol for protected members.
Static Members
A static member is a property or method that all instances of a class share. Unlike an instance
property, where each object gets its own value for that property, there is only one value for a
class’s static property. It is common for all objects.
Static members are used when some data or operations are independent of the instances of the
class.
Programs Output
<?php
Class Student 1
{
public $name;
public $USN;
public $address;
public $avg;
public static $StudentCount = 0;
function __construct($n,$usn,$add,$avg)
{
$this->name = $n;
$this->USN= $usn;
$this->address = $add;
$this->avg = $avg;
self::$StudentCount++;
}
}
$s1 = new Student("abc","1120","Bangalore",66);
echo Student::$StudentCount;
?>
Output:
In the UML notation the shared property is underlined to indicate its static nature.
Class
Student Object
+ StudentCount: int $s1:Student
+ name: String + self::$StudentCount
+ USN: String + name: Shwetha
+ address: String + USN: 123
+ avg: float + address: Bangalore
+ construct(int, String, String, String) + avg: 66
+ construct(int, String, String, String)
Class Constants
Constant values are stored more efficiently as class constants using ‘const’ keyword. There will
be the constant values as long as they are not calculated or updated.
Eg - const EARLIEST_DATE = 'January 1, 1200';
Unlike all other variables, constants don’t use the $ symbol when declaring or using them. They
can be accessed both inside and outside the class using self::EARLIEST_DATE in the class and
classReference::EARLIEST_DATE outside.
Objects can be reused across the program. The software is easier to maintain, as any changes in
the structure need to change only the class. OO concepts enables faster development and easier
maintenance of the software.
Data Encapsulation
Object-oriented design enables the possibility of encapsulation (hiding), that is, restricting
access to an object’s internal components (properties and methods). Another way of
understanding encapsulation is: it is the hiding of an object’s implementation details.
In properly encapsulated class, the properties and methods, are hidden using the private access
specifier and these properties and methods are accessed to outside the class using the public
methods. Thus we can restrict the usage of required properties and methods.
The hidden properties are accessed and modified using public methods commonly called getters
and setters (or accessors and mutators). A getter returns a variable’s value does not modify the
property. It is normally called without parameters, and returns the property from within the class.
The below example shows the modified Student class with getters and setters. Some of the
properties are private. These properties cannot be accessed or assigned from outside the class,
the getters and setters.
Program Output
<?php
class student{
// Properties
public $name;
public $USN;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
echo $s1->get_name();
echo "<br>";
Two forms of the UML class diagram for our data encapsulated class are –
Class Class
Student Student
- name: String - name: String
- USN: String - USN: String
+ address: String + address: String
+ avg: float + avg: float
+ construct(int, String, String, String) + construct(int, String, String, String)
+ getname() : String
+ getUSN() : String
+ setname(String) : void
+ setUSN(String) : void
The first UML diagram includes, all the getter and setter methods. UML diagram may also
exclude the getter and setter methods from a class as shown in the second diagram.
Inheritance
Inheritance enables you to create new PHP classes that reuse, extend, and modify the behavior
that is defined in another PHP class. A class that is inheriting the properties and methods from
another class is said to be a subclass, a derived class or a child class. The class that is being
inherited is called a superclass , a base class or a parent class.
When a class inherits from another class, it inherits all of its public and protected methods and
properties. Just as in Java, a PHP class is defined as a subclass by using the extends keyword.
Base Class
Student
- name: String
+ USN: String
+ address: String
+ avg: float
+ construct(int, String, String, String)
# display( ): void
Derived Class
Student
- sports: int
- academic: int
+ construct(int, String, String, String,int,int)
+ total ( ):void
+ display( ): void
Program
<?php
Class Student
{
private $name;
public $USN;
public $address;
public $avg;
function __construct($n,$usn,$add,$avg)
{
$this->name = $n;
$this->USN= $usn;
$this->address = $add;
$this->avg = $avg;
}
protected function display()
{
echo $this->name;
}
}
function __construct($n,$usn,$add,$avg,$s,$ac)
{
parent:: __construct($n,$usn,$add,$avg);
$this->sports= $s;
$this->academic= $ac;
}
If a member has to be available to subclasses but not anywhere else, it can be done by using the
protected access modifier. ‘name’ member of base class can be accessed in base class only as it
is private. It is displayed using ‘$this->name’ in base class.
Inheriting Methods
Every method defined in the base/parent class can be overridden when extending a class, by
declaring a function with the same name. A simple example of overriding is done in the previous
program, the display( ) method of subclass FeeDetails overrides the display( ) method of parent
class.
Vinutha G K,Shwetha G N,Sunitha Page 28
Module IV – Arrays, Classes & Objects, Exception Handling in PHP 18CS63
To access a public or protected method or property defined within a base class from within a
subclass, use the member name with parent:: prefix.
Parent Constructors
To invoke a parent constructor from the derived class’s constructor, use the parent:: syntax and
call the constructor on the first line parent:: _ _construct(). This is similar to calling other parent
methods, except that to use it we must call it at the beginning of constructor.
Polymorphism
Polymorphism is the OO concept, where the object can act differently at different times. Even if
the same function name is used.
Overriding of methods in two or more derived classes takes place, the actual method called will
depend on the type of the object. In the below example program, the display ( ) method is
defined in both the derived classes. The method accessed depends on the object used to access
the function.
<?php
Class Student
{
private $name;
public $USN;
public $address;
public $avg;
function construct($n,$usn,$add,$avg)
{
$this->name = $n;
$this->USN= $usn;
$this->address = $add;
$this->avg = $avg;
}
protected function display()
{
echo $this->name;
}
}
function construct($n,$usn,$add,$avg,$s,$ac)
{
parent:: construct($n,$usn,$add,$avg);
function construct($n,$usn,$add,$avg)
{
parent:: construct($n,$usn,$add,$avg);
}
?>
OUTPUT:
Sajeev total fee is 28000 Amith No fees
The same display( ) method is invoked by two different objects. First the display( ) function of
FeeDetails class is invoked and then the display( ) function of Scholarship class is invoked.
The run time decision of determining the function to be invoked at run time, is called dynamic
dispatching. Just as each object can maintain its own properties, each object also manages its
own table of methods. This means that two objects of the same type can have different
implementations with the same name.
Interfaces provide a mechanism for defining what a class can do without specifying how it does
it. Interfaces are defined using the interface keyword. It looks similar to PHP classes, except an
interface contains no properties and its methods do not have method bodies defined.
Eg -
interface Viewable {
public function getmessage();
public function getData();
}
Notice that an interface contains only public methods, and instead of having a method body, each
method is terminated with a semicolon.
In PHP, a class can be said to implement an interface, using the implements keyword:
This means then that the class ‘FeeDetails’ must provide implementations for the getmessage()
and getData() methods.Implementing an interface allows a class to become more formal about
the behavior it promises to provide. The same interface can be inherited by more than one class.
It helps in the implementation of multiple inheritance.
PHP allows implementing two or more interfaces. The UML diagram to denote the interfaces
include the <<interface>> stereotype. Classes that implement an interface are shown to
implement using the same hollow triangles as inheritance but with dotted lines.
Base Class
Student Interface
- name: String <<interface>>
+ USN: String Viewable
+ address: String + getmessage ( ) : void
+ avg: float + getData ( ):void
+ construct(int, String, String, String)
# display( ): void
Derived Class
Student
- sports: int
- academic: int
+ construct(int, String, String, String,int,int)
+ total ( ):void
+ display( ): void
To determine what interfaces this class has implemented, use the function class_implements(),
which returns an array of all the interfaces implemented by this class or its parents.
$allInterfaces = class_implements($x);
Types of Errors
There are three different types of website problems:
• Expected errors
• Warnings
• Fatal errors
An expected error is an error that routinely occurs during an application. The most common
example of this type of error is as a result of user inputs, ie. , entering letters when numbers were
expected. The web application should be developed such that, we expect the user to not always
enter expected values. Users will leave fields blank, enter text when numbers were expected,
type in too much or too little text, forget to click certain things, and click things they should not
etc.
Not every expected error is the result of user input. Web applications that rely on connections to
externalities such as database management systems, legacy software systems, or web services is
expected to occasionally fail to connect. So there should be some type of logic that verifies the
errors in code, check the user inputs and check if it contains the expected values.
Another type of error is warnings, which are problems that generate a PHP warning message
(which may or may not be displayed) but will not halt the execution of the page. For instance,
calling a function without a required parameter will generate a warning message but not stop
execution. While not as serious as expected errors, these types of incidental errors should be
eliminated by the programmer.
The fatal errors, which are serious in that the execution of the page will terminate unless
handled in some way. These types of errors are exceptional and unexpected, such as a required
input file being missing or a database table or field disappearing. These types of errors need to be
reported so that the developer can try to fix the problem, and also the page needs to recover
gracefully from the error so that the user is not excessively puzzled or frustrated.
Exception
In the context of PHP, error and exception is not the same. An error is some type of problem that
generates a nonfatal warning message or that generates an error message that terminates the
program’s execution. An exception refers to objects that are of type Exception and which are
used in conjunction with the object-oriented try . . . catch language construct for dealing with
runtime errors.
This type of coding requires the programmer to know ahead of time what code is going to
generate an error condition and also result in a great deal of code duplication. The advantage of
the try . . . catch mechanism is that it allows the developer to handle a wider variety of
exceptions in a single catch block.
PHP also uses the try . . . catch programming construct to programmatically deal with exceptions
at runtime. The catch construct expects some type of parameter of type Exception. The
Exception built-in class provides methods for accessing not only the exception message, but also
the line number of the code that generated the exception and the stack trace, both of which can
be helpful for understanding where and when the exception occurred.
finally {
// PHP code here that will be executed after try or after catch
}
The finally block is optional. Any code within it will always be executed after the code in the try
or in the catch blocks, even if that code contains a return statement. It is typically used if the
developer wants certain things to do regardless of whether an exception occurred, such as closing
a connection or removing temporary files.
It is also possible in PHP to programmatically throw an exception via the throw keyword. An
exception is thrown when an expected programming assumption is not met. It also possible to
rethrow an exception within a catch block.
function processArray($array)
{
// make sure the passed parameter is an array with values
if ( empty($array) ) {
throw new Exception('Array with values expected');
}
// process the array code
...
}
Note: PHP.ini is a configuration file, that is used to customize behavior of PHP at runtime. It
consists of settings for different values such as register global variables, display errors, log
errors, max uploading size setting, maximum time to execute a script and other configurations.
When PHP Server starts up it looks for PHP.ini file first to load various values for settings.
The possible levels for error_reporting are defined by predefined constants(the default setting is
zero, that is, no reporting).
When logging is turned on, error reporting will be sent to either the operating system’s error log
file or to a specified file in the site’s directory. If error messages is to be saved in a log file in the
user’s directory, the file name and path can be set via the error_log setting.
ini_set('error_log', '/restricted/my-errors.log');
You can also programmatically send messages to the error log at any time via the error_log()
***********************************************************