Unit-Iv Overview of Classes, Objects, and Instances: Encapsulation
Unit-Iv Overview of Classes, Objects, and Instances: Encapsulation
Unit-Iv Overview of Classes, Objects, and Instances: Encapsulation
UNIT-IV
OVERVIEW OF CLASSES, OBJECTS, AND INSTANCES
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:
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:
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:
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);
?>
The typographical error has resulted in the addition of a new rice property to the $polly
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);
?>
$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:
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.
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
{
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
}
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
• 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
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.
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:
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.
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.
The Code
<?php
$a=10;
function display()
{
echo ―The value of a is‖.$a;
}
function __destruct()
{
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:
Stream: A stream is a sequence of data bytes which were read from or written to 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:
resource fopen (string fname, string mode [, bool useincpth [, resource zcontext]])
fopen()
resource fopen (string resource, string mode [, int use_include_path[, resource zcontext]])
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 :
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.";
} 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.
<?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
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()
<?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:
<?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);
?>
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.
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.
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
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.
<?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‘);
}