Webchap 4
Webchap 4
Webchap 4
Objectives:
After reading this chapter you should be entertained and learned:
1. What is PHP?
2. The Life-cycle of the PHP.
3. Why PHP?
4. Getting Started with PHP.
5. A Bit About Variables.
6. HTML Forms.
7. Building A Simple Application.
8. Programming Languages Statements Classification.
9. Program Development Life-Cycle.
10. Structured Programming.
11. Object Oriented Programming Language.
Figure 4.1 The Relationship between the PHP, the Web Browser, and the MySQL DBMS
89
WEB
SERVER
Gets Page
<HTML>
<?php PHP code ?>
HTTP Request
</HTML>
(url)
<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<p>Hello World</p>
</body>
</html>
You should check that this has worked by viewing the file in a browser of your choice. It is
vital that you view the file from the server and not any local copy that you could open in the
browser so that the PHP can be interpreted. We will now add our first piece of PHP code to
generate the words 'Hello World' rather than have them coded within the HTML.
90
Note: To distinguish the PHP parts from the normal HTML (which would get displayed as typed)
and any PHP code (that we want interpreted) we use <?php and ?> which mean begin PHP
code and end of PHP code. After the first instance of <?php on the page a shorthand <? will
suffice.
We are now going to replace the static 'Hello World' in the HTML with a piece of PHP
code that echoes the words instead. The 'echo' function is the easiest one to use in PHP and
basically echoes anything within the quotes as output. Thus our first piece of PHP code would look
like this:
or
<?php
$greeting = “Hello World!”
print $greeting;
php?>
or
<script language=“PHP”>
$hello = “Hello”;
$world = “World!”;
print $hello . $world
</script>
....and when we integrate that code into our HTML we end up with...
<html>
<head>
<title>My First PHP Script</title>
</head>
<body>
<h4>Example One</h4>
<p><?php echo "Hello World"; ?></p>
</body>
</html>
Also note that after the echo command there is a semicolon to indicate that the line of PHP
code is finished. Again save the file to your webspace, then preview it in a browser and you can see
that the output should be the same as the first time. Congratulations - you have now made your first
PHP script.
Obviously the reason that we want to use PHP rather than normal static HTML is to allow
us to use values that can change, or dynamic content from a database. These values are stored in
variables that can then be echoed as part of the HTML as with 'Hello World' above. For those that
haven't come across variables before, it is useful to think of a variable as an imaginary box into
which any value may be placed so depending what we ask the database the value stored in the
variable will be different. For those of you who have used variables in different contexts before,
PHP (like PERL) doesn't require you to declare a variable (tell the interpreter that the variable exists
and what type of variable it is) before using it. PHP knows that something is a variable by the fact
that the name is preceded with a dollar sign like so - $variable.
As a first example of a variable we will assign the words 'Hello World' to a variable and
then echo that variable. So replace
91
<h4>Example One</h4>
<p><?php echo "Hello World"; ?></p>
with
<h4>Example Two</h4>
<?php
$firstvar = "Hello World";
echo $firstvar;
?>
Again save the file, upload it to your webserver and preview the file in your browser
(changing the Example number will help you see that the file is actually changing).
4.5.1 Constants:
<?php
$arr = array("somearray" => array(6 => 5, 13 => 9,
"a" => 42));
echo $arr["somearray"][6]; // 5
echo $arr["somearray"][13]; // 9
echo $arr["somearray"]["a"]; // 42
?>
92
• Operators
– Contains all of the operators like in C and Perl (even the ternary)
• Statements
– if, if/elseif
– Switch/case
– for, while, and do/while loops
– Include and require statements for code reuse
• Date and Time Functions
– getdate, mkdate, date, gettimeofday, localtime, strtotime, time
– Directory Functions
– Platform independent
– Error Handling Functions
– Recover from warnings and errors
– Filesystem Functions
– Access flat files
– Check directory, link, and file status information
– Copy, delete, and rename files
– IMAP Functions
– Manipulate mail boxes via the IMAP protocol
– LDAP Functions
– Works with most LDAP servers
– Mail Functions
– mail($recipient, $subject, $message)
– Database Functions
– dba: dbm-style abstraction layer
– dBase
– Frontbase
– Informix
– Ingres II
– Interbase
– mSQL
– MySQL
– Oracle
– PostgreSQL
– SQL Server
– MING
– Macromedia Flash
– PDF
– Create/manipulate PDF files dynamically
– Semaphore and Socket Functions
– Available only on Unix
– Session Management Functions
– Feature: PHP is not a strongly typed language
– Variables can be created anywhere in your code
As well as containing what is known as a text string, a variable can also contain a numeric value:
<h4>Example Three</h4>
<?php
$firstvar = 5;
echo $firstvar;
?>
93
And when we assign a numeric value to a variable we can manipulate that variable as if it was a
number. This is achieved by using operators much like we would in maths.
Operator Function
+ Add
- Subtract
* Multiply
/ Divide
For example to multiply the $firstvar by 2 and store that value in a $secondvar:
<h4>Example Four</h4>
<?php
$firstvar = 5;
$secondvar = $firstvar * 2;
echo $secondvar;
?>
<h4>Example Five</h4>
<?php
$firstvar = 5;
$firstvar = $firstvar + 1;
echo $firstvar;
?>
Reassigning the value of a variable to itself plus 1 can also be expressed like this:
<h4>Example Six</h4>
<?php
$firstvar = 5;
$firstvar += 1;
echo $firstvar;
?>
If you want to do more than one calculation you can use brackets to separate the sections of
the overall calculation. Bringing everything we've done so far to one line of PHP code, we can take
a variable, add 1 to its value, multiply that new value by 2 and then store the new value in the
original variable name.
<h4>Example Seven</h4>
<?php
$firstvar = 5;
$firstvar = ($firstvar + 1) * 2;
echo $firstvar;
?>
You can add new text to a text string variable as well, although this process is called
concatenation and uses a different operator to achieve this. To join two pieces of text together the '.'
operator is used between each piece of text. This 'joining' can occur as part of assigning a value to a
variable or as part of the echo function. Let's look at some examples.
To assign the word 'Hello' to $firstvar and add the word ' World' assigning the result to
$secondvar (notice the space before 'World' is needed to preserve a space between the two words).
94
<h4>Example Eight</h4>
<?php
$firstvar = "Hello";
$secondvar = $firstvar . " World";
echo($secondvar);
?>
<h4>Example Nine</h4>
<?php
echo "Hello" . " World";
?>
Or to join the $firstvar to the word 'World' as part of the echo function.
<h4>Example Ten</h4>
<?php
$firstvar = "Hello";
echo $firstvar . " World";
?>
Thus we have seen the main ways in which a variable can be manipulated.
4.5.5 Arrays:
An array is simply a list of values. Each value can be retrieved independently of one another
and can also be changed without affecting the other values. Like most things it's better to learn by
seeing examples.
An array can be created empty before any data is entered, but the more common way is to
create an array and adding values at the same time. This is done in a similar way to assigning a
variable value except we can use the array() function to specify the list of values:
<?php
$firstarray = array("Hello","World");
?>
An array can also be initialised without the array function simply byadding values. Note the
square brackets [] are used to reference individual values in the array as we'll see in a moment.
<?php
$firstarray[] = "Hello";
$firstarray[] = "World";
?>
These values can now be echoed as well, by using a number to identify (in the order in
which they were entered) the values within the square brackets.
<h4>Example Eleven</h4>
<?php
$firstarray[] = "Hello";
$firstarray[] = "World";
echo $firstarray[0] . " " . $firstarray[1];
?>
95
Note: In the above example we have also concatenated the text with a space in between the words.
This is better than adding a space as part of the variable, either before or after one of the words, as
we may wish to use the variables in a different order which would make the positioning of the space
incorrect when all the variables were echoed.
You can then add other values to the array and echo those as well.
<h4>Example Twelve</h4>
<?php
$firstarray[] = "Hello";
$firstarray[] = "World";
echo $firstarray[0] . " " . $firstarray[1];
$firstarray[] = "How";
$firstarray[] = "Are";
$firstarray[] = "You";
echo " " . $firstarray[2] . " " . $firstarray[3]. " " . $firstarray[4];
?>
This type of simple array is very useful if you want to store and retrieve values of the same
type, but seeking specific information based on a number can be a bit tricky, so it's sometimes better
to use an associative array.
With this type of array we store a label or key as well as a value that can be retrieved. These
Key/Value pairs can again be created in two ways; by using the array() function, or directly
assigning a value. This differs from the examples above as we're specifying two things this time.
The key is specified and then the value like so:
key => value
To illustrate this lets create a capital city array where the Values will be the cities and the the
countries are the Keys.
<h4>Example Thirteen</h4>
<?php
$cities = array(
'france' => 'paris',
'germany' => 'berlin',
'uk' => 'london'
);
?>
We can echo these values by using the Key name in place of a number.
<h4>Example Thirteen</h4>
<?php
$cities = array (
'france' => 'paris',
'germany' => 'berlin',
'uk' => 'london'
);
echo $cities['france'] . " " . $cities['germany'] . " " . $cities['uk'];
?>
We could again do this without the array() function and just assign Key/Value pairs to the
array.
96
<h4>Example Fourteen</h4>
<?php
$cities['france'] = 'paris';
$cities['germany'] = 'berlin';
$cities['uk'] = 'london';
echo $cities['france'] . " " . $cities['germany'] . " " . $cities['uk'];
?>
The final thing to mention about arrays is that we can change a value of individual array
members by manipulating those members the same way as with the variables.
<h4>Example Fifteen</h4>
<?php
$math_array['total'] = 0;
$math_array['one'] = 1;
$math_array['five'] = 5;
$math_array['eight'] = 8;
echo $math_array['one'] . "+" . $math_array['five'] . "+" .
$math_array['eight'];
$math_array['total'] = ($math_array['one'] + $math_array['five'] +
$math_array['eight']);
echo "=" . $math_array['total'];
?>
So far we have used variables to which we have assigned values, but there are also several
predefined variables that exist within PHP that hold values about the server environment. The
naming conventions for these 'Superglobals' (so called due to their persistent presence) has changed
with recent releases of PHP. These sections will use the type seen in PHP 4.2.0 and above. In earlier
PHP releases it was possible to access the values stored in these variables by preceding the variable
name with a $. For example to get the host name of the server we would use $SERVER_NAME.
Now we have to do things slightly differently as these values are stored in global associative arrays
instead. The important arrays that we will use straight away in these sections are:
$_GET - Variables provided as part of http get (such as those passed to the script in a URL).
$_POST - Variables provided as part of http post (such as those from an HTML form).
$_REQUEST - Stores all array members of $_POST and $_GET (and $_COOKIES).
At this point we won't concern ourselves with how these can be used, just to know that they
exist is fine.
97
4.6 HTML Forms:
To begin our look at forms we will create a file called myvars.htm which contains an HTML
form that is set up to send the data it collects to our variables.php file.
<html>
<head>
<title>My Variables HTML Form</title>
</head>
<body>
<h4>My HTML Form</h4>
<form name="myform" method="get" action="variables.php">
Enter Firstname: <input type="text" name="firstname"><br>
Enter Lastname: <input type="text" name="lastname"><br><br>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
The important parts of this are that the 'action' attribute is pointing towards the correct file
(variables.php) and that the names given to each text input field are the same as the array elements
in the script, otherwise nothing will happen. Upload this file, try typing different names, and look at
the effect on the output. You will also notice that there is still a QUERY_STRING in the URL
when we submit the form. This is because we have used the 'GET' method. There is another that we
will look at and use, the POST method.
The 'POST' method includes its information in the 'body' of a http request rather than in the
URL and thus cannot be seen. We can see this in action if we change the method in our myvars.htm
file
<form name="myform" method="post" action="variables.php">
When the form is submitted to the PHP script, nothing happens. That is because our script is
using the $_GET array which stores values passed via the GET method, rather the $_POST array
(that stores the values passed by POST). Thus we need to change this in the variables.php script to
accept POST values.
<html>
<head>
<title>My Variables PHP Script</title>
</head>
<body>
<p>The query string is: <?php echo $_SERVER['QUERY_STRING']; ?></p>
<p>Firstname: <? echo $_POST['firstname']; ?></p>
<p>Lastname: <? echo $_POST['lastname']; ?></p>
</body>
</html>
There is a third array that stores values. If we want the values to be available no matter
which method was used to pass the variables then we could use the $_REQUEST array (which
combines the members from both $_GET and $_POST).
<html>
<head>
<title>My Variables PHP Script</title>
</head>
98
<body>
<p>The query string is: <?php echo $_SERVER['QUERY_STRING']; ?></p>
<p>Firstname: <? echo $_REQUEST['firstname']; ?></p>
<p>Lastname: <? echo $_REQUEST['lastname']; ?></p>
</body>
</html>
One of the most common applications of any server side scripting language is processing
HTML forms. You’ll start learning PHP by implementing an order form for Bob’s Auto Parts, a
fictional spare parts company.
Right now, Hesham’s HTML programmer has gotten as far as setting up an order form for
the parts that Hesham sells. The order form is shown in Figure 4.4. This is a relatively simple order
form, similar to many you have probably seen while surfing. The first thing Hesham would like to
be able to do is know what his customer ordered, work out the total of the customer’s order, and
how much sales tax is payable on the order.
The first file is to display a form that passes values into another program
1 <html >
2 <form action=processorder.php method=post >
3 <table border=0 >
4 <tr bgcolor=#cccccc >
5 <td width=150>Item</td >
6 <td width=15>Quantity</td >
7 <tr />
8 <tr >
9 <td>Tires</td >
10 <td align=center >
11 <input type='text' name='tireqty' size=3 maxlength=3></td>
12 <tr />
13 <tr >
14 <td>Oil</td >
15 <td align=center >
16 <<input type='text' name='oilqty' size=3 maxlength=3></td >
17 <tr />
18 <tr >
19 <td>Spark Plugs</td >
20 <td align=center >
21 <input type='text' name='sparkqty' size=3 maxlength=3></td>
22 <tr />
23 <tr >
24 <td colspan=2 align=right >
25 <input type=submit value='Submit'></td >
26 <tr />
27 <table />
28 <form />
29 <html />
30
31
Figure 4.3 Listing of the First Form using the web server Apache
32
The first thing to notice is that we have set the form’s action to be the name of the PHP
script that will process the customer’s order. (We’ll write this script next.) In general, the value of
the ACTION attribute is the URL that will be loaded when the user presses the submit button. The
data the user has typed in the form will be sent to this URL via the method specified in the
METHOD attribute, either GET (appended to the end of the URL) or POST (sent as a separate
packet).
99
The second point you should notice is the names of the form fields—tireqty, oilqty, and
sparkqty. We’ll use these names again in our PHP script. Because of this, it’s important to give your
form fields meaningful names that you can easily remember when you begin writing the PHP script.
Some HTML editors will generate field names like field23 by default. These are difficult to
remember. Your life as a PHP programmer will be easier if these names reflect the data that is typed
into the field.
In Line #2 , “processorder.php” is the name of the program to be called
when clicking the “submit” button on the displayed windows.
Line #25 displays a submit button. The word Submit is the value to be
displayed on the button.
Save the file and load it in your browser by filling out Hesham’s form and clicking the
Submit button.
Notice how the PHP code we wrote was embedded inside a normal-looking HTML file. Try
viewing the source from your browser. You should see this code:
<html>
<head>
<title>Hesham’s Auto Parts - Order Results</title>
</head>
<body>
<h1>Hesham’s Auto Parts</h1>
100
<h2>Order Results</h2>
<p>Order processed.</p></body>
</html>
Let us continue and discuss the complete program that gets the values of the passed variabl
of the form shown in figure 4.4.
Figur 4.5 shows the listing of the program “processorder.php”
101
There are actually four different styles of PHP tags we can use. Each of the following
fragments of code is equivalent.
4.7.4.1 Short style:
<? echo “<p>Order processed.”; ?>
This is the tag style that will be used in this book. It is the default tag that PHP developers
use to code PHP. This style of tag is the simplest and follows the style of an SGML (Standard
Generalized Markup Language) processing instruction. To use this type of tag—which is the
shortest to type—you either need to enable short tags in your config file, or compile PHP with short
tags enabled. You can find more information on how to do this in Appendix A.
4.7.4.2 XML style:
<?php echo “<p>Order processed.”; ?>
This style of tag can be used with XML (Extensible Markup Language) documents. If you
plan to serve XML on your site, you should use this style of tag.
4.7.4.3 SCRIPT style:
<SCRIPT LANGUAGE=’php’> echo “<p>Order processed.”; </SCRIPT>
This style of tag is the longest and will be familiar if you’ve used JavaScript or VBScript. It
can be used if you are using an HTML editor that gives you problems with the other tag styles.
4.7.4.4 ASP style:
<% echo “<p>Order processed.”; %>
This style of tag is the same as used in Active Server Pages (ASP). It can be used if you
have enabled the asp_tags configuration setting. You might want to use this style of tag if you are
using an editor that is geared towards ASP or if you already program in ASP.
4.8 Programming Languages Statements Classification:
Any programming language statements could be classified into three main classes:
sequence, selection, and repetition. Figure 4.5 shows theses classes.
Sequence Selection Repetition
if structure if/else structure while structure
false false
do/while structure
Sequence
switch structure
true
break
false
true
false
break
true
false for structure
break
true
false
true
false
102
Each programming language syntax would represent the staments which would fit in those
classes. Acording to the ANSI standard, recent programming languages represent the syntax of all
statements in the same style. Some minor differences may be found to distinguage a product from
others.
Analysis
Design
Implement
Test
Maintain
Figure 4.6 shows the most important phases of a program development life-cycle
4.9.1 Analysis:
In this phase, anylst should deliver the analysis document containing the main function of
the program, its input and output details, and the required process on the inputs to get the outputs.
4.9.2 Design:
In this phase, designer should deliver the design document containing the detailed steps to
get the required outputs from the given inputs (keeping into consideration all possible edit checks),
also, creating the data dictionary. The most famous ways to express a program design are:
algorithms, flowcharts, or Nazi-Schniderman charts.
4.9.2.1 Algorithms:
They are English-like language that express in details the steps of any task.
4.9.2.2 Flowcharts:
A flowchart is composed of a group of known symbols that would be used to express the
logical sequence of performing a specified task.
103
Compare Start
Process
Directions
End Print
Another way of expressing the logical steps of a program taking into consideration
structured programming. Figure 4.8 shows the main components of the Nazi-Schinderman charts.
switch structure
Figure 4.9 Rule-1 a sequence composed of one block having one input and one output
Rule-2: Any block can be divided into two or more blocks keeping Rule-1 as shown in Figure 4.10.
104
Rule-2 Rule-2 Rule-2
Figure 4.10 Rule-2 Each block can be divided into two or more blocks keeping Rule-1
Rule-3: When having selection inside any block can be seen as shown in Figure 4.11.
Rule-3
Rule-3 Rule-3
Figure 4.11 Rule-3 when having a selection block, we can deal with it as shown above
Rule-4: No blocks intersection, but nested blocks are allowed as shown in Figure 4.12.
105
Nested blocks are allowed
You can use a sequence
No Intersection is allowed
of blocks
Everything that the software object knows (state) and can do (behavior) is expressed by the
variables and the methods within that object. A software object that modeled your real-world
bicycle would have variables that indicated the bicycle's current state: its speed is 10 mph, its pedal
cadence is 90 rpm, and its current gear is the 5th gear. Figure 4.14 illustrates a bicycle modeled as a
software object.
1
… Most definitions related to the “Object Oriented” were taken from java.sun.com.
106
4.11.1 Information hiding:
An object has a public interface that other objects can use to communicate with it. The
object can maintain private information and methods that can be changed at any time without
affecting the other objects that depend on it. You don't need to understand the gear mechanism on
your bike to use it.
Figure 4.15 shows the relationship between goals, principles, and techniques of the Object
Oriented.
Figure 4.15 the relationship between goals, principles, and techniques of the Object Oriented
107
4.11.4.2 Modularity:
The source code for an object can be written and maintained independently of the source
code for other objects. Also, an object can be easily passed around in the system. You can give your
bicycle to someone else, and it will still work.
4.11.4.3 Abstraction:
Abstraction is the distillation of a complicated system to its most fundamental parts and
describes these parts in a simple, precise language (naming different parts and describing their
functionality) – as the “Oxford Dictionary” describes the word meaning.
4.11.4.4 Abstract Data Type (ADT):
Abstraction Data Type is a mathematical model of a data structure that specifies the type of
data stored, the operations supported on them, and the types of parameters of operations. An ADT
specifies what each operation does, but not how it does.
4.11.4 Object Oriented Programming Techniques:
The main techniques of “Object Oriented Programming” are: interface and typing,
inheritance and polymorphism, and classes and objects.
4.11.4.1 What Is an Interface?
An interface is a contract in the form of a collection of method and constant declarations.
When a class implements an interface, it promises to implement all of the methods declared in that
interface.
The bicycle class and its class hierarchy defines what a bicycle can and cannot do in terms
of its "bicycleness." But bicycles interact with the world on other terms. For example, a bicycle in a
store could be managed by an inventory program. An inventory program doesn't care what class of
items it manages as long as each item provides certain information, such as price and tracking
number. Instead of forcing class relationships on otherwise unrelated items, the inventory program
sets up a protocol of communication. This protocol comes in the form of a set of constant and
method definitions contained within an interface. The inventory interface would define, but not
implement, methods that set and get the retail price, assign a tracking number, and so on.
To work in the inventory program, the bicycle class must agree to this protocol by
implementing the interface. When a class implements an interface, the class agrees to implement all
the methods defined in the interface. Thus, the bicycle class would provide the implementations for
the methods that set and get retail price, assign a tracking number, and so on.
You use an interface to define a protocol of behavior that can be implemented by any class
anywhere in the class hierarchy. Interfaces are useful for the following:
108
4.11.4.2 What Is a Message?
Software objects interact and communicate with each other using messages.
A single object alone is generally not very useful. Instead, an object usually appears as a component
of a larger program or application that contains many other objects. Through the interaction of these
objects, programmers achieve higher-order functionality and more complex behavior. Your bicycle
hanging from a hook in the garage is just a bunch of titanium alloy and rubber; by itself, the bicycle
is incapable of any activity. The bicycle is useful only when another object (you) interacts with it
(pedal).
Software objects interact and communicate with each other by sending messages to each
other. When object A wants object B to perform one of B's methods, object A sends a message to
object B
Sometimes, the receiving object needs more information so that it knows exactly what to do;
for example, when you want to change gears on your bicycle, you have to indicate which gear you
want. This information is passed along with the message as parameters.
The next figure shows the three components that comprise a message:
These three components are enough information for the receiving object to perform the
desired method. No other information or context is required.
Messages provide two important benefits.
• An object's behavior is expressed through its methods, so (aside from direct variable
access) message passing supports all possible interactions between objects.
• Objects don't need to be in the same process or even on the same machine to send
and receive messages back and forth to each other.
109
Generally speaking, objects are defined in terms of classes. You know a lot about an object
by knowing its class. Even if you don't know what a penny-farthing is, if I told you it was a bicycle,
you would know that it had two wheels, handle bars, and pedals.
Object-oriented systems take this a step further and allow classes to be defined in terms of
other classes. For example, mountain bikes, racing bikes, and tandems are all kinds of bicycles. In
object-oriented terminology, mountain bikes, racing bikes, and tandems are allsubclasses of the
bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, racing bikes, and
tandems. This relationship is shown in the following figure.
Each subclass inherits state (in the form of variable declarations) from the superclass.
Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the like. Also,
each subclass inherits methods from the superclass. Mountain bikes, racing bikes, and tandems
share some behaviors: braking and changing pedaling speed, for example.
However, subclasses are not limited to the state and behaviors provided to them by their
superclass. Subclasses can add variables and methods to the ones they inherit from the superclass.
Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an extra set
of gears with a lower gear ratio.
Subclasses can alsooverride inherited methods and provide specialized implementations for
those methods. For example, if you had a mountain bike with an extra set of gears, you would
override the "change gears" method so that the rider could use those new gears.
You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy,
can be as deep as needed. Methods and variables are inherited down through the levels. In general,
the farther down in the hierarchy a class appears, the more specialized its behavior.
The Object class is at the top of class hierarchy, and each class is its descendant (directly or
indirectly). A variable of type Object can hold a reference to any object, such as an instance of a
class or an array. Object provides behaviors that are required of all objects running in the Java
Virtual Machine. For example, all classes inherit Object's toString method, which returns a string
representation of the object.
Inheritance offers the following benefits:
110
• Programmers can implement superclasses called abstract classes that define
"generic" behaviors. The abstract superclass defines and may partially implement the
behavior, but much of the class is undefined and unimplemented. Other
programmers fill in the details with specialized subclasses.
4.11.4.4 Polymorphism
The concept of polymorphism (literally "many forms") means the ability to hide different
implementations behind a common interface.
This means using the same name (or symbol) for several different procedures or functions
(i.e., operations) and allowing the compiler to choose the correct one based on the signatures (i.e.,
on the number, types, and order of the parameters). This choice can be done statically at the time
the program is compiled.
In PHP 5, extensions written in C can overload almost every aspect of the object syntax. It
also allows PHP code to overload a limited subset that is most often needed. This section covers the
overloading abilities that you can control from your PHP code.
Java does not currently support parameterized class definitions. (The template facility in
C++ and the generic facility in Ada are examples of parametric polymorphism.)
In the real world, you often have many objects of the same kind. For example, your bicycle
is just one of many bicycles in the world. Using object-oriented terminology, we say that your
bicycle object is an instanceof the class of objects known as bicycles. Bicycles have some state
(current gear, current cadence, two wheels) and behavior (change gears, brake) in common.
However, each bicycle's state is independent of and can be different from that of other bicycles.
111
When building bicycles, manufacturers take advantage of the fact that bicycles share
characteristics, building many bicycles from the same blueprint. It would be very inefficient to
produce a new blueprint for every individual bicycle manufactured.
In object-oriented software, it's also possible to have many objects of the same kind that
share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle
manufacturers, you can take advantage of the fact that objects of the same kind are similar and you
can create a blueprint for those objects. A software blueprint for objects is called a class.
The class for our bicycle example would declare the instance variables necessary to contain
the current gear, the current cadence, and so on, for each bicycle object. The class would also
declare and provide implementations for the instance methods that allow the rider to change gears,
brake, and change the pedaling cadence, as shown in the figure 4.19.
Figure 4.19 The declaration of a class can provide implementations for instance methods
After you've created the bicycle class, you can create any number of bicycle objects from
the class. When you create an instance of a class, the system allocates enough memory for the
object and all its instance variables. Each instance gets its own copy of all the instance variables
defined in the class.
112
Figure 4.20 Creation of any number of bicycle objects from the class
In addition to instance variables, classes can define class variables. A class variable contains
information that is shared by all instances of the class. For example, suppose that all bicycles had
the same number of gears. In this case, defining an instance variable to hold the number of gears is
inefficient; each instance would have its own copy of the variable, but the value would be the same
for every instance. In such situations, you can define a class variable that contains the number of
gears. All instances share this variable. If one object changes the variable, it changes for all other
objects of that type. A class can also declare class methods. You can invoke a class method directly
from the class, whereas you must invoke instance methods on a particular instance.
overriding
Providing a different implementation of a method in a subclass of the class that originally
defined the method.
hierarchy
A classification of relationships in which each item except the top one (known as the root) is
a specialized form of the item above it. Each item can have one or more items below it in
the hierarchy.
method
113
A function defined in a class.
superclass
A class from which a particular class is derived, perhaps with one or more classes in
between.
subclass
A class that is derived from a particular class, perhaps with one or more classes in between.
class variable
A data item associated with a particular class as a whole--not with particular instances of the
class. Class variables are defined in class definitions. Also called a static field.
class method
A method that is invoked without reference to a particular object. Class methods affect the
class as a whole, not a particular instance of the class. Also called a static method.
variable
An item of data named by an identifier. Each variable has a type, such as int or Object, and a
scope.
instance method
Any method that is invoked with respect to an instance of a class. Also called simply a
method.
instance variable
Any item of data that is associated with a particular object. Each instance of a class has its
own copy of the instance variables defined in the class. Also called a field.
4.12 A Sample of Questions:
Part 1: ............
Fill in the circle that represents the correct choice for
each question in the given answer sheet (more than one choice for
any question would be considered wrong answer).
An example of a correct answer:
114
Part 2 : . . . . . . . . . . . . . . . .
Fill in the circle that represents the correct choice for
each question in the given answer sheet (more than one choice for
any question would be considered wrong answer).
1) A variable is an item of data named by an identifier. Each
one has a type, such as int or Object, and a scope.
a. True
b. False
2) A polymorphism is a blueprint or prototype that defines the
variables and the methods common to all objects of a certain
kind.
a. True
b. False
3) The concept of polymorphism (literally "many forms") means
the ability to hide different implementations behind a common
interface.
a. True
b. False
Part 3: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
This part consists of fill in The Blank questions. Given
below a table of words to choose from. On the answer sheet, put
the number of the appropriate word in the space available for that
question.
1 2 3 4 5
subclass OS OSI an object API
6 7 8 9 10
FOSS OSS .htm superclass overriding
115