Unit-Iv Overview of Classes, Objects, and Instances: Encapsulation

Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Page 1 of 22

UNIT-IV
OVERVIEW OF CLASSES, OBJECTS, AND INSTANCES

OBJECT ORIENTED PROGRAMMING:

The birth of object-oriented programming represented a major paradigm shift in


development strategy, refocusing attention on an application‘s data rather than its logic. To put it
another way, OOP shifts the focus from a program‘s procedural events toward the real-life
entities ultimately models. The result is an application that closely resembles the world around
us.
This section examines three of OOP‘s foundational concepts: encapsulation, inheritance,
and polymorphism. Together, these three ideals form the basis for the most powerful
programming model yet devised.

Encapsulation
Programmers enjoy taking things apart and learning how all of the little pieces work
together. Although gratifying, attaining such in-depth knowledge of an item‘s inner workings
isn‘t a requirement. For example, millions of people use a computer every day, yet few know
how it actually works. The same idea applies to automobiles, microwaves, and any number of
other items. We can get away with such ignorance through the use of interfaces.
Object-oriented programming promotes the same notion of hiding the inner workings of
the application by publishing well-defined interfaces from which each application component
can be accessed. Rather than get bogged down in the gory details, OOP-minded developers
design each application component so that it is independent from the others, which not only
encourages reuse but also enables the developer to assemble components like a puzzle rather
than tightly lash, or couple, them together. These components are known as objects, and objects
are created from a template known as a class, which specifies what sorts of data the object might
contain and the behavior one would expect. This strategy offers several advantages:

• The developer can change the application implementation without affecting the
object user because the user‘s only interaction with the object is via its interface.
• The potential for user error is reduced because of the control exercised over the
user‘s interaction with the application.

Inheritance
The many objects constituting our environment can be modeled using a fairly welldefined
set of rules. In object-oriented terms, these various employee types inherit the general employee
definition, including all of the characteristics and behaviors that contribute to this definition.
The object-oriented development methodology places great stock in the concept of
inheritance. This strategy promotes code reusability because it assumes that one will be able to
use well-designed classes (i.e., classes that are sufficiently abstract to allow for reuse) within
numerous applications.

Polymorphism
Polymorphism, a term originating from the Greek language that means ―having multiple
forms,‖ defines OOP‘s ability to redefine, or morph, a class‘s characteristic or behavior
depending upon the context in which it is used.
PREPARED BY: K.RAVI KUMAR III-IT Page 1
Page 2 of 22

Returning to the example, suppose that a behavior titled clockIn was included within the
employee definition. For employees of class Clerk, this behavior might involve actually using a
time clock to timestamp a card. For other types of employees, Programmer for instance, clocking
in might involve signing on to the corporate network. Although both classes derive this behavior
from the Employee class, the actual implementation of each is dependent upon the context in
which ―clocking in‖ is implemented.
This is the power of polymorphism. These three key OOP concepts, encapsulation,
inheritance, and polymorphism, are further introduced as they apply to PHP through this chapter
and the next.

Classes:
Our everyday environment consists of countless entities: plants, people, vehicles, food...I
could go on for hours just listing them. Each entity is defined by a particular set of characteristics
and behaviors that ultimately serves to define the entity for what it is. For example, a vehicle
might be defined as having characteristics such as color, number of tires, make, model, and
capacity, and having behaviors such as stop, go, turn, and honk horn. In the vocabulary of OOP,
such an embodiment of an entity‘s defining attributes and behaviors is known as a class.
Classes are intended to represent those real-life items that you‘d like to manipulate within
an application. For example, if you want to create an application for managing a public library,
you‘d probably want to include classes representing books, magazines, employees, special
events, patrons, and anything else that would require oversight. Each of these entities embodies a
certain set of characteristics and behaviors, better known in OOP as fields and methods,
respectively, that define the entity as what it is. PHP‘s generalized class creation syntax follows:
class Class_Name
{
// Field declarations defined here
// Method declarations defined here
}
Listing 6-1 depicts a class representing employees.
//Class Creation
class Employee
{
private $name;
private $title;
protected $wage;
protected function clockIn() {
echo "Member {$this->name} clocked in at ".date("h:i:s");
}
protected function clockOut() {
echo "Member $this->name clocked out at ".date("h:i:s");
}
}
Titled Employee, this class defines three fields, name, title, and wage, in addition to
two methods, clockIn and clockOut. Don‘t worry if you‘re not familiar with some of
the grammar and syntax;

Objects:
PREPARED BY: K.RAVI KUMAR III-IT Page 2
Page 3 of 22

A class provides a basis from which you can create specific instances of the entity the
class models, better known as objects. For example, an employee management application may
include an Employee class. You can then call upon this class to create and maintain specific
instances, Sally and Jim, for example. Objects are created using the new keyword, like this:

$employee = new Employee();


Once the object is created, all of the characteristics and behaviors defined within the class
are made available to the newly instantiated object. Exactly how this is accomplished is revealed
in the following sections.

Creating Instances Using Constructors : -

To create a new instance of a class (also referred to as instantiating a class), the


new operator in conjunction with the class name called as though it were a function. When
used in this way, it acts as what is known as the class constructor and serves to initialize the
instance.
$tweety = new Bird('Tweety', 'canary');

This creates a specific instance of Bird and assigns it to the variable named $tweety. In
other words, you have defined $tweety as a Bird. So far you have not actually defined any
members for the Bird class,

<?php
class Bird
{
function __construct($name, $breed)
{
$this->name = $name;
$this->breed = $breed;
}
}
?>

How It Works/Variations
This is about as simple a class definition as you can write in PHP 5. As is the case in PHP
4, a PHP 5 class is defined in a block of code that begins with the class keyword and the name of
the class. In most cases, a class is not going to be useful unless you can create instances of it. To
accomplish this task, you need a class constructor. In PHP 5, you do this by defining a method
with the name __construct(); this method is called whenever you create a new instance of the
class.
The $this keyword has a special purpose: it allows you to refer to the instance from
With in the class definition. It works as a placeholder and means, ―the current instance of
this class.‖ The Bird class constructor assigns the string 'Tweety' to the name property of the
instance you are creating and the string 'canary' to its breed property. You can put this to
the test like so:

PREPARED BY: K.RAVI KUMAR III-IT Page 3


Page 4 of 22

The Code

<?php
class Bird
{
function __construct($name, $breed)
{
$this->name = $name;
$this->breed = $breed;
$tweety->price = 24.95;
}
}
$tweety = new Bird('Tweety', 'canary',24.5);
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$tweety->name, $tweety->breed, $tweety->price);
?>
The resulting output is as follows:

Tweety is a canary and costs 24.50.

Using Default Constructors


Suppose also that most—say, 80 percent—of your birds are priced at $15. Wouldn‘t it be
more convenient if all your Bird instances came with prices already set to that amount and you
were required to set the prices of only the remaining 20 percent? PHP lets you set default
values for function parameters and for class constructors. The following example shows a
slightly revised Bird class.

The Code
<?php
class Bird
{
function __construct($name='No-name', $breed='breed unknown', $price = 15)
{
$this->name = $name;
$this->breed = $breed;
$this->price = $price;
}
}
$aBird = new Bird();
$tweety = new Bird('Tweety', 'canary');
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$aBird->name, $aBird->breed, $aBird->price);
$tweety->price = 24.95;
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$tweety->name, $tweety->breed, $tweety->price);
?>

PREPARED BY: K.RAVI KUMAR III-IT Page 4


Page 5 of 22

Here is the output:


No-name is a breed unknown and costs $15.00.
Tweety is a canary and costs $15.00.
Tweety is a canary and costs $24.95.

Setting Object Properties


A page or two back, we said it is better to include all properties of an object in its class
definition rather than creating them dynamically. This is for two reasons. First, as we mentioned,
you want to be sure all instances of a class have the same properties; otherwise, what happens
when you forget to set a price for a Bird when some other part of your code expects there to be
one? Second, when you assign a value to an object property, PHP does not check to see whether
the property already exists. This means that it is all too easy to make a mistake that can be
difficult to detect later, such as this one:
<?php
class Bird
{
function __construct($name='No-name', $breed='unknown', $price = 15)
{
$this->name = $name;
$this->breed = $breed;
$this->price = $price;
}
}
$polly = new Bird('Polynesia', 'parrot');
$polly->rice = 54.95; // ooooops...!
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$polly->name, $polly->breed, $polly->price);
?>
The output from this script is as follows:
Polynesia is a parrot and costs $15.00.
Just in case you have not spotted the error, you can add the following line of debugging
code to this script to see all of Polynesia‘s properties at a glance:

The function get_object_vars() makes a handy addition to your object-oriented


programming toolkit. It takes any object as a parameter and returns an array whose keys are the
names of the object‘s properties and whose values are the values of the properties. The output in
this case is as follows:
Array
(
[name] => Polynesia
[breed] => parrot
[price] => 15
[rice] => 54.95
)

The typographical error has resulted in the addition of a new rice property to the $polly

PREPARED BY: K.RAVI KUMAR III-IT Page 5


Page 6 of 22

object, which is not what you wanted at all. You can avoid this sort of stuff by using methods
to get and set properties rather than setting them directly. Let‘s rewrite the class, except this
time we will include a setPrice() method.
The Code
<?php
class Bird
{
function __construct($name='No-name', $breed='unknown', $price = 15)
{
$this->name = $name;
$this->breed = $breed;
$this->price = $price;
}
function setPrice($price)
{
$this->price = $price;
}
}
$polly = new Bird('Polynesia', 'parrot');
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$polly->name, $polly->breed, $polly->price);
$polly->setPrice(54.95);
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$polly->name, $polly->breed, $polly->price);
?>

The output from this example is as follows:


Polynesia is a parrot and costs $15.00.
Polynesia is a parrot and costs $54.95.
Variations
What happens if you change the line containing the call to the setPrice() method to
something like the following?
$polly->setPice(54.95);
Because you are attempting to call a method that has not been defined, the result is an
error message: Fatal error: Call to undefined method Bird::setPice() in /home/www/php5/bird-
5.php on line 22

Controlling Access to Class Members


We will start the discussion of this topic with a modified version of the previous example.
The following shows the new Bird class, including a complete collection of get and set methods.
The Code
<?php
// file bird-get-set.php
class Bird
{
function __construct($name='No-name', $breed='unknown', $price = 15)
{

PREPARED BY: K.RAVI KUMAR III-IT Page 6


Page 7 of 22

$this->name = $name;
$this->breed = $breed;
$this->price = $price;
}
function setName($name)
{
$this->name = $name;
}
function setBreed($breed)
{
$this->breed = $breed;
}
{
$this->price = $price < 0 ? 0 : $price;
}
function getName()
{
return $this->name;
}
function getBreed()
{
return $this->breed;
}
function getPrice()
{
return $this->price;
}
{
printf("<p>%s is a %s and costs \$%.2f.</p>\n",
$this->name, $this->breed, $this->price);
}
}
$magpie = new Bird('Malaysia', 'magpie', 7.5);
$magpie->display();
?>

Notice that we have written the setPrice() method in such a way that the price cannot be
set to a negative value; if a negative value is passed to this method, the price will be set to zero.
function setPrice($price)

To save some repetitive typing of the printf() statement that you have been using to
output all the information you have about a given Bird object, you can add a new method named
display() that takes care of this task: function display()
Variations
Now let‘s create a new instance of Bird. Let‘s say that before you have the chance to
write this example, the shop sells Polynesia the parrot; so, you will use a magpie this time. First,
call the constructor with some plausible values:

PREPARED BY: K.RAVI KUMAR III-IT Page 7


Page 8 of 22

You can verify that the class is working as expected by viewing the output in a browser:
Malaysia is a magpie and costs $7.50. Because the neighborhood cats are begging you to get rid
of the magpie—even if it means paying someone to take it off your hands—try using setPrice()
to set the magpie‘s asking price to a negative number:

$magpie->setPrice(-14.95);
$magpie->display();

The setPrice() method prevents you from setting the price to a value less than zero:
Malaysia is a magpie and costs $0.00.
This allows you to control how class members can be accessed through three keywords:

• public: The property or method can be accessed by any other code. This is the default
visibility for all class members in PHP 5. (Note: In PHP 4, all class members are public.)

• private: A private class member can be accessed only from within the same class.
Attempting to do so from outside the class will raise an error.

• protected: A class member that is declared as protected may be accessed from within
the class and from within any class that extends that class.

Now that you know about visibility, fixing the problem you encountered is simple. Just
insert the following into the Bird class before the definition of the constructor:
private $name;
private $breed;
private $price;

Extending Classes:
PHP having one of their most powerful features, which lies in the ability to reuse an
existing class when creating one or more new ones. This technique is known as extending a class.
Extending classes is useful when you have multiple objects that have some but not all
properties or methods in common. Rather than write a separate class for each object that
duplicates the members that are common to all, you can write a generic class that contains
these common elements, extend it with subclasses that inherit the common members, and
then add those that are specific to each subclass.

PREPARED BY: K.RAVI KUMAR III-IT Page 8


Page 9 of 22

The above shows an example in which we have reworked the Bird class from earlier in
this chapter and split it up into three classes. The new Parrot and Canary classes are subclasses of
Bird. The fact that they each inherit the methods and properties of the Bird class is indicated
by the arrows, whose heads point to the parent class
The following is some PHP 5 code that implements these three classes. Bird has three
properties ($name, $price, and $breed), all of which are private. You can set the first two of
these with the public methods setName() and setPrice(), respectively, or in the class constructor.
You can set the breed only from the Bird class constructor; because the setBreed() method is
private, it can be called only from within Bird, not from any other code. Since $breed has no
default value, you will receive a warning if you do not set it in the constructor. This seems
reasonable—you could rename a bird or change its price easily enough in real life, but you will
not often be transforming a pigeon into a bird of paradise unless you are a magician. Notice that
you have changed this from the earlier incarnations of this class where you had a default value
for this property; here you are saying, ―I do not want anyone adding a bird to my inventory
unless they say exactly what sort of bird it is.‖ You also force the programmer to name the bird
when it is created; however, the price does have a default value.

The Code
<?php
// file: bird-multi.php
// example classes for inheritance example
class Bird
{

PREPARED BY: K.RAVI KUMAR III-IT Page 9


Page 10 of 22

private $name;
private $breed;
private $price;
public function __construct($n, $b, $p)
{
$this->setName($n);
$this->setBreed($b);
$this->setPrice($p);
}
public function setName($n)
{
$this->name = $n;
}
private function setBreed($b)
{
$this->breed = $b;
}
public function setPrice($p)
{
$this->price = $p;
}
public function getName()
{
return $this->name;
}
public function getBreed()
{
return $this->breed;
}
public function getPrice()
{
return $this->price;
}
public function display()
{
printf("<p>%s is a %s and costs \$%.2f.</p>",
$this->getName(),
$this->getBreed(),
$this->getPrice());
}
} // end class Bird

class Parrot extends Bird


{
public function birdCall()
{
printf("<p>%s says: *squawk*</p>\n", $this->getName());

PREPARED BY: K.RAVI KUMAR III-IT Page 10


Page 11 of 22

}
public function __construct($name)
{
parent::__construct($name, 'parrot', 25);
}
public function curse()
{
printf("<p>%s curses like a sailor.</p>\n", $this->getName());
}
} // end class Parrot

class Canary extends Bird


{
public function birdCall($singing=FALSE)
{
if($singing)
printf("<p>%s says: *twitter*</p>\n", $this->getName());
else
parent::birdCall();
}
public function __construct($name)
{
parent::__construct($name, 'canary');
}
}
?>

Abstract Classes and Methods:


The Bird::birdCall() method you used in the previous example has a fallback in case a
derived class does not override it. Now let‘s suppose you are not interested in providing a
default behavior for this method; instead, you want to force all Bird subclasses to provide
birdCall() methods of their own. You can accomplish this using another feature that is new to
PHP in version 5—abstract classes and methods
An abstract method is one that is declared by name only, with the details of the
implementation left up to a derived class. You should remember three important facts when
working with class abstraction:

• Any class that contains one or more abstract methods must itself be declared as
abstract.
• An abstract class cannot be instantiated; you must extend it in another class and then
create instances of the derived class. Put another way, only concrete classes can be
instantiated.
• A class that extends the abstract class must implement the abstract methods of the
parent class or itself be declared as abstract.

Let‘s update the Bird class so that its birdCall() method is abstract. We will not repeat
the entire class listing here—only two steps are necessary to modify Bird. The first step is to

PREPARED BY: K.RAVI KUMAR III-IT Page 11


Page 12 of 22

replace the method declaration for Bird::birdCall() with the following:


abstract public function birdCall();
An abstract method has no method body; it consists solely of the abstract keyword
followed by the visibility and name of the function, the function keyword, a pair of parentheses,
and a semicolon. What this line of code says in plain English is, ―Any class derived from this
one must include a birdCall() method, and this method must be declared as public.‖ The second
step is to modify the class declaration by prefacing the name of the class with the abstract
keyword, as shown here: abstract class Bird
Figure 2-3 shows a UML diagram of the modified three-class package. Abstract classes
and methods are usually indicated with their names in italics; alternatively, you can use the
stereotype <<abstract>> for this purpose.

Now you need to consider how birdCall() is implemented in Parrot and Canary.
Parrot::birdCall () is fine the way it is; it is not abstract, and it does not refer to the birdCall()
method of the parent class. With Canary‘s birdCall() method, however, you have a problem:
you cannot invoke the parent‘s version of the method because it is abstract. However, it is not
much work to reemployment birdCall() so that this does not happen.

Interfaces:
An interface specifies what a class must do but not how it does it.
An interface as a template that tells you what methods a class should expose but leaves
the details up to you. Interfaces are useful in that they can help you plan your classes without
immediately getting bogged down in the details.

PREPARED BY: K.RAVI KUMAR III-IT Page 12


Page 13 of 22

To declare an interface, simply use the interface keyword, followed by the name of the
interface. Within the body of the interface, list declarations (delimited, as with classes, by
braces, {...}) for any methods to be defined by classes that implement the interface.

Looking at the Bird class, you might deduce that you are really representing two different
sorts of functional units: a type of animal (which has a name and a breed) and a type of product
(which has a price). Let‘s generalize these into two interfaces, like so:

The Code
interface Pet
{
public function getName();
public function getBreed();
}
interface Product
{
public function getPrice();
}
To show that a class implements an interface, you add the implements keyword plus the
name of the interface to the class declaration. One advantage that interfaces have over abstract
classes is that a class can implement more than one interface, so if you wanted to show that
Bird implements both Pet and Product, you would simply rewrite the class declaration for
Bird, as shown here:

abstract class Bird implements Pet, Product

An interface is represented in UML diagrams by a box with two compartments, the top
one containing the stereotype <<Interface>> followed by the name of the interface and the
bottom one containing the signatures of the interface‘s methods. Figure 2-4 shows the updated
Bird class diagram with the Pet and Product interfaces and their relationship with the Bird class.
Note that the implementation by a class of an interface is indicated by a dashed arrow
that points from the class to the interface that it implements.

PREPARED BY: K.RAVI KUMAR III-IT Page 13


Page 14 of 22

For example, if you need to write classes to represent additional pets for sale by the pet
store, you can, by implementing Pet and Product in those classes, guarantee that they will have
the same methods that Bird and its subclasses do.

Using Class Destructors:


In PHP 5, classes can have destructors as well as constructors. A destructor is simply a
method that is guaranteed to be invoked whenever an instance of the class is removed from
memory, either as the result of a script ending or because of a call to the unset() function.
For example, suppose that when a user of your e-commerce website—represented by an
instance of a SiteUser class—leaves the site, you want to make sure that all the user‘s preference
data is saved to the site‘s user database. Suppose further that SiteUser already has a savePrefs()
method that accomplishes this task; you just need to make sure it is called when the user logs
out. In that case, the class listing might include something like the following.

The Code
<?php
$a=10;
function display()

{
echo ―The value of a is‖.$a;
}
function __destruct()
{

PREPARED BY: K.RAVI KUMAR III-IT Page 14


Page 15 of 22

Unset($a);
}
Display();
?>
From this program it won‘t display anything.

As you can see from this listing, all you need to do is to add a __destruct() method to the class
containing whatever code you want to be executed when an instance of the class ceases to exist.

File Handling:

File: A file is a collection of data.

Stream: A stream is a sequence of data bytes which were read from or written to a file.

The basic file operations are:


Naming a file
Opening a file
Reading from a file
Writing to a file
Closing a file

Communication with files follows the pattern of opening a stream to a file, reading from
or writing to it, and then closing the stream. When you open a stream, you get an integer that
refers to the open stream. Each time you want to read from or write to the file, you use this
stream identifier. Internally PHP uses this integer to refer to all the necessary information for
communicating with the file.
Opening Files:

The first task you must accomplish when working with a file (be it a .txt file, an .xml file, or
another file) is to open the file. To open a file on the local file system, you use the fopen function.
It takes a name of a file and a string that defines the mode of communication. This may be r for
read-only or w for write-only, among other modes. Two other functions create file streams. You
may open a pipe with the popen function or you may open a socket connection with the fsockopen
function. If you have much experience with UNIX, you will recognize pipes as temporary
streams of data between executing programs.

The following example uses two pertinent file-related functions: file_exists() checks (relatively)
for a file‘s existence, and fopen() attempts to open a file. The prototypes for the functions are as
follows:

bool file_exists ( string filename )

resource fopen (string fname, string mode [, bool useincpth [, resource zcontext]])

fopen()
resource fopen (string resource, string mode [, int use_include_path[, resource zcontext]])

PREPARED BY: K.RAVI KUMAR III-IT Page 15


Page 16 of 22

The fopen() function binds a resource to a stream, or handler. Once bound, the script can
interact with this resource via the handle. Most commonly, it‘s used to open files for reading
and manipulation.

The mode, assigned at the time a resource is opened, determines the level of access available
to that resource. The various modes are defined in Table :

Table: File Modes


Mode Description
r Read-only. The file pointer is placed at the beginning of the file.
r+ Read and write. The file pointer is placed at the beginning of the file.
w Write only. Before writing, delete the file contents and return the file
pointer to the beginning of the file. If the file does not exist, attempt to
create it.
w+ Read and write. Before reading or writing, delete the file contents and
return the file pointer to the beginning of the file. If the file does not exist,
attempt to create it.
a Write only. The file pointer is placed at the end of the file. If the file does
not exist, attempt to create it. This mode is better known as Append.
a+ Read and write. The file pointer is placed at the end of the file. If the file
does not exist, attempt to create it. This process is known as appending to
the file.
b Open the file in binary mode.
T Open the file in text mode.

If the resource is found on the local file system, PHP expects the resource to be available
by either the local or relative path prefacing it. Alternatively, you can assign fopen()‘s
use_include_path parameter the value of 1, which will cause PHP to consider the paths specified
in the include_path configuration directive.

The final parameter, zcontext, is used for setting configuration parameters specific to the
file or stream, and for sharing file- or stream-specific information across multiple fopen()
requests.

The Code
<?php
//sample7_1.php
//First, declare the file you want to open.
$file = "samplefile1.txt";
//Now, you use the file_exists() function to confirm its existence.
if (file_exists ($file)){
//Then you attempt to open the file, in this case for reading.
try {
if ($readfile = fopen ($file, "r")){
//Then you can work with the file.
echo "File opened successfully.";

PREPARED BY: K.RAVI KUMAR III-IT Page 16


Page 17 of 22

} else {
//If it fails, you throw an exception.
throw new exception ("Sorry, the file could not be opened.");
}
} catch (exception $e) {
echo $e->getmessage();
}
} else {
echo "File does not exist.";
}
?>

Output:
File opened successfully.

fclose():
boolean fclose (resource filehandle)

Good programming practice dictates that you should destroy pointers to any resources once
you‘re finished with them. The fclose() function handles this for you, closing the previously
opened file pointer specified by filehandle, returning TRUE on success and FALSE otherwise.
The filehandle must be an existing file pointer opened using fopen() or fsockopen().

Once you have opened a file stream, you can read or write to it using commands like fgets, and
fputs. The given below Listing demonstrates this. Notice that a while loop is used to get each line
from the example file. It tests for the end of the file with the feof function. When you are
finished with a file, end of file or not, you call the fclose function. PHP will clean up the
temporary memory it sets aside for tracking an open file.

Listing : Writing and Reading from a File

<?php
/*
** open file for writing
*/
$filename = "data.txt";
if(!($myFile = fopen($filename, "w")))
{
print("Error: ");
print("'$filename' could not be created\n");
exit;
}
//write some lines to the file
fputs($myFile, "Save this line for later\n");
fputs($myFile, "Save this line too\n");
//close the file
fclose($myFile);
PREPARED BY: K.RAVI KUMAR III-IT Page 17
Page 18 of 22

/*
** open file for reading
*/
if(!($myFile = fopen($filename, "r")))
{
print("Error:");
print("'$filename' could not be read\n");
exit;
}
while(!feof($myFile))
{
//read a line from the file
$myLine = fgets($myFile, 255);
print("$myLine <BR>\n");
}
//close the file
fclose($myFile);
?>

Output:
Save this line for later
Save this line too

Reading from a File


PHP offers numerous methods for reading data from a file, ranging from reading in just
one character at a time to reading in the entire file with a single operation. Many of the most
useful functions are:

fgetc()
string fgetc (resource handle)
The fgetc() function reads a single character from the open resource stream specified by
handle. If the EOF is encountered, a value of FALSE is returned.

fgets()
fgets (resource handle [, int length])
The fgets() function returns either length – 1 bytes from the opened resource referred to by
handle, or everything it has read up to the point that a newline or the EOF is encountered. If the
optional length parameter is omitted, 1,024 characters is assumed. In most situations, this
means that fgets() will encounter a newline character before reading 1,024 characters, thereby
returning the next line with each successive call. An example follows:
<?php
$fh = fopen("/home/www/data/users.txt", "rt");
while (!feof($fh)) echo fgets($fh);
fclose($fh);
?>

fgetss()

PREPARED BY: K.RAVI KUMAR III-IT Page 18


Page 19 of 22

string fgetss (resource handle, int length [, string allowable_tags])


The fgetss() function operates similarly to fgets(), except that it strips any HTML and PHP tags
from handle. If you‘d like certain tags to be ignored, include them in the allowable_tags
parameter. As an example, consider a scenario in which authors are expected to submit their
work in HTML format using a specified subset of HTML tags. Of course, the authors don‘t
always follow instructions, so the file must be scanned for tag misuse before it can be published.
With fgetss(), this is trivial:

<?php
/* Build list of acceptable tags */
$tags = "<h2><h3><p><b><a><img>";
/* Open the article, and read its contents. */
$fh = fopen("article.html", "rt");
while (!feof($fh)) {
$article .= fgetss($fh, 1024, $tags);
}
fclose($fh);
/* Open the file up in write mode
and write $article contents. */
$fh = fopen("article.html", "wt");
fwrite($fh, $article);
fclose($fh);
?>

fread()
string fread (resource handle, int length)
The fread() function reads length characters from the resource specified by handle. Reading
stops when the EOF is reached or when length characters have been read. Note that, unlike
other read functions, newline characters are irrelevant when using fread(); therefore, it‘s often
convenient to read the entire file in at once using filesize() to determine the number of characters
that should be read in:

<?php
$file = "/home/www/data/users.txt";
$fh = fopen($file, "rt");
$userdata = fread($fh, filesize($file));
fclose($fh);
?>
The variable $userdata now contains the contents of the users.txt file.

readfile()
int readfile (string filename [, int use_include_path])
The readfile() function reads an entire file specified by filename and immediately outputs it to
the output buffer, returning the number of bytes read. Enabling the optional use_include_path
parameter tells PHP to search the paths specified by the include_path configuration parameter.
After sanitizing the article discussed in the fgetss() section, it can be output to the browser
quite easily using readfile(). This revised example is shown here:

PREPARED BY: K.RAVI KUMAR III-IT Page 19


Page 20 of 22

<?php
$file = "/home/www/articles/gilmore.html";
/* Build list of acceptable tags */
$tags = "<h2><h3><p><b><a><img>";
/* Open the article, and read its contents. */
$fh = fopen($file, "rt");
while (!feof($fh))
$article .= fgetss($fh, 1024, $tags);
fclose($fh);
/* Open the article, overwriting it with the sanitized material */
$fh = fopen($file, "wt");
fwrite($fh, $article);
fclose($fh);
/* Output the article to the browser. */
$bytes = readfile($file);
?>

Moving the File Pointer


It‘s often useful to jump around within a file, reading from and writing to various locations.
Several PHP functions are available for doing just this.

fseek()
int fseek (resource handle, int offset [, int whence])
The fseek() function moves the handle‘s pointer to the location specified by offset. If the
optional parameter whence is omitted, the position is set offset bytes from the beginning of the
file. Otherwise, whence can be set to one of three possible values, which affect the pointer‘s
position:
• SEEK_CUR: Sets the pointer position to the current position plus offset bytes.
• SEEK_END: Sets the pointer position to the EOF plus offset bytes. In this case, offset
must be set to a negative value.
• SEEK_SET: Sets the pointer position to offset bytes. This has the same effect as omitting
whence.

ftell()
int ftell (resource handle)
The ftell() function retrieves the current position of the file pointer‘s offset within the resource
specified by handle.
rewind()
int rewind (resource handle)
The rewind() function moves the file pointer back to the beginning of the resource specified by
handle.

Writing to a File
This section highlights several of the functions used to output data to a file.

PREPARED BY: K.RAVI KUMAR III-IT Page 20


Page 21 of 22

fwrite()
int fwrite (resource handle, string string [, int length])
The fwrite() function outputs the contents of string to the resource pointed to by handle. If
the optional length parameter is provided, fwrite() will stop writing when length characters
have been written. Otherwise, writing will stop when the end of the string is found. Consider
this example:
<?php
$subscriberInfo = "Jason Gilmore|[email protected]";
$fh = fopen("/home/www/data/subscribers.txt", "at");
fwrite($fh, $subscriberInfo);
fclose($fh);
?>

fputs()
int fputs (resource handle, string string [, int length])
The fputs() function operates identically to fwrite(). Presumably, it was incorporated into
the language to satisfy the terminology preferences of C/C++ programmers.

Using Exceptions
PHP 5 introduces a much-improved mechanism for handling errors. Like many of PHP 5‘s new
features, exceptions may already be familiar to you if you are a Java programmer. If you are not,
here is your chance to become acquainted with them.

An exception is an abnormal condition that arises in the program sequence code. An exception is
a run time error.

Handling Exceptions in PHP can be done using the following key words:
try
catch and
throw

The try block consists of block of code that can be monitored for exception. When ever an
exception arises in the program sequence code PHP constructs an object for it and it throw to
default exception handler. A try block must atleast have one catch block. Even nesting of try is
also allowed in PHP. The catch block contains the code that can be executed when the exception
rises. When the exception rises in try block it is sent to exception handler using keyword throw.
Thus, catch block acts as an exception handler.

The syntax of exception handling is:

try
{
function some action();
if(some function that causes the exception)
throw new Exception(String message);

//..
function another action();
PREPARED BY: K.RAVI KUMAR III-IT Page 21
Page 22 of 22

if(other function causes the exceptions)


throw new Exception(String message);
//….
}
catch Exception $e
{
//block of code that handles the exception
}

Having understood the theory behind the exception handling, and have had the knowledge of
various keywords like try, catch and throw, it is right time to see in practice. Let‘s begin the
concept of exception handling with a simple PHP script:

<?php
$a=10;
$b=0;
Echo ‗ Division of ‗.$a.‘ and ‗.$b. ‗is: ‗.($a/$b);
?>

The above given example program seems to be absolutely correct, but when run PHP terminates
the script.

Here is an example that demonstrates the exception handling:

<?php
try
{
$a=10;
$b=0;
// causes an exception
if($a/$b)
echo ‗ Division of ‗.$a.‘ and ‗.$b. ‗is: ‗.($a/$b);
else
throw new Exception(‗Division by Zero Exception‘);
}

//define the handler


catch(Exception $e)
{
Echo ‗Error:‘.$getMessage();
}
?>
Output:

Error: Division by Zero Exception.

*** THE END ***

PREPARED BY: K.RAVI KUMAR III-IT Page 22

You might also like