Tải bản đầy đủ (.pdf) (5 trang)

PHP and MySQL Web Development - P36 doc

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (74.34 KB, 5 trang )

142
Chapter 5 Reusing Code and Writing Functions
functions are slower and use more memory than iteration, so you should use iteration
wherever possible.
In the interest of completeness, we will look at a brief example shown in Listing 5.5.
Listing 5.5 recursion.php—It Is Simple to Reverse a String Using
Recursion—The Iterative Version Is Also Shown
function reverse_r($str)
{
if (strlen($str)>0)
reverse_r(substr($str, 1));
echo substr($str, 0, 1);
return;
}
function reverse_i($str)
{
for ($i=1; $i<=strlen($str); $i++)
{
echo substr($str, -$i, 1);
}
return;
}
In this listing, we have implemented two functions. Both of these will print a string in
reverse.The function reverse_r() is recursive, and the function reverse_i() is itera-
tive.
The reverse_r() function takes a string as parameter.When you call it, it will pro-
ceed to call itself, each time passing the second to last characters of the string. For exam-
ple, if you call
reverse_r('Hello');
it will call itself a number of times, with the following parameters:
reverse_r('ello');


reverse_r('llo');
reverse_r('lo');
reverse_r('o');
reverse_r('');
Each call the function makes to itself makes a new copy of the function code in the
server’s memory, but with a different parameter. It is like pretending that we are actually
calling a different function each time.This stops the instances of the function from get-
ting confused.
With each call, the length of the string passed in is tested.When we reach the end of
the string (strlen()==0), the condition fails.The most recent instance of the function
07 525x ch05 1/24/03 3:36 PM Page 142
143
Next
(reverse_r('')) will then go on and perform the next line of code, which is to echo
the first character of the string it was passed—in this case, there is no character because
the string is empty.
Next, this instance of the function returns control to the instance that called it, name-
ly reverse_r('o').This prints the first character in its string—"o"—and returns control
to the instance that called it.
The process continues—printing a character and then returning to the instance of the
function above it in the calling order—until control is returned back to the main pro-
gram.
There is something very elegant and mathematical about recursive solutions. In most
cases, however, you are better off using an iterative solution.The code for this is also in
Listing 5.5. Note that it is no longer (although this is not always the case with iterative
functions) and does exactly the same thing.
The main difference is that the recursive function will make copies of itself in memo-
ry and incurs the overhead of multiple function calls.
You might choose to use a recursive solution when the code is much shorter and
more elegant than the iterative version, but it will not happen often in this application

domain.
Although recursion appears more elegant, programmers often forget to supply a ter-
mination condition for the recursion.This means that the function will recur until the
server runs out of memory, or until the maximum execution time is exceeded, whichev-
er comes first.
Further Reading
The use of include(), require(), function, and return are also explained in the
online manual.To find out more about concepts such as recursion, pass by value/refer-
ence, and scope that affect many languages, you can look at a general computer science
text book, such as Dietel and Dietel’s C++ How To Program.
Next
Now that you are using include files, require files, and functions to make your code
more maintainable and reusable, the next chapter addresses object oriented software and
the support offered in PHP. Using objects allows you to achieve goals similar to the con-
cepts presented in this chapter, but with even greater advantages for complex projects.
07 525x ch05 1/24/03 3:36 PM Page 143
07 525x ch05 1/24/03 3:36 PM Page 144
6
Object-Oriented PHP
This chapter explains concepts of object-oriented development and shows how they can
be implemented in PHP.
Key topics in this chapter include
n
Object-oriented concepts
n
Creating classes, attributes, and operations
n
Using class attributes
n
Calling class operations

n
Inheritance
n
Calling class methods
n
Designing classes
n
Writing the code for your class
Object-Oriented Concepts
Modern programming languages usually support or even require an object-oriented
approach to software development. Object-oriented (OO) development attempts to use
the classifications, relationships, and properties of the objects in the system to aid in pro-
gram development.
Classes and Objects
In the context of OO software, an object can be almost any item or concept—a physical
object such as a desk or a customer; or a conceptual object that only exists in software,
such as a text input area or a file. Generally, we are most interested in conceptual objects
including real world objects that need to be represented in software.
08 525x ch06 1/24/03 3:35 PM Page 145
146
Chapter 6 Object-Oriented PHP
Object-oriented software is designed and built as a set of self-contained objects with
both attributes and operations that interact to meet our needs. Attributes are properties or
variables that relate to the object. Operations are methods, actions, or functions that the
object can perform to either modify itself or for some external effect.
Object-oriented software’s central advantage is its capability to support and encourage
encapsulation—also known as data hiding. Essentially, access to the data within an object is
only available via the object’s operations, known as the interface of the object.
An object’s functionality is bound to the data it uses.We can easily alter the details of
how the object is implemented to improve performance, add new features, or fix bugs

without having to change the interface, which can have ripple effects throughout the project.
In other areas of software development, OO is the norm and function oriented soft-
ware is considered old fashioned. For a number of reasons, most Web scripts are unfortu-
nately still designed and written using an ad hoc approach following a function oriented
methodology.
A number of reasons for this exist.The majority of Web projects are relatively small
and straightforward.You can get away with picking up a saw and building a wooden
spice rack without planning your approach and you can successfully complete the major-
ity of Web software projects in the same way because of their small size. However, if you
picked up a saw and attempted to build a house without formal planning, you won’t get
quality results, if you get results at all—the same is true for large software projects.
Many Web projects evolve from a set of hyperlinked pages to a complex application.
These complex applications, whether presented via dialog boxes and windows or via
dynamically generated HTML pages, need a properly thought out development method-
ology. Object orientation can help you to manage the complexity in your projects,
increase code reusability, and thereby reduce maintenance costs.
In OO software, an object is a unique and identifiable collection of stored data and
operations that operate on that data. For instance, we might have two objects that repre-
sent buttons. Even if both have a label “OK”, a width of 60 pixels, a height of 20 pixels,
and any other attributes that are identical, we still need to be able to deal with one but-
ton or the other. In software, we have separate variables that act as handles (unique iden-
tifiers) for the objects.
Objects can be grouped into classes. Classes represent a set of objects that might vary
from individual to individual, but must have a certain amount in common. A class con-
tains objects that all have the same operations behaving in the same way and the same
attributes representing the same things, although the values of those attributes will vary
from object to object.
The noun bicycle can be thought of as a class of objects describing many distinct
bicycles with many common features or attributes—such as two wheels, a color and a
size, and operations, such as move.

My own bicycle can be thought of as an object that fits into the class bicycle. It has
all the common features of all bicycles including a move operation that behaves the
same as most other bicycles’ move—even if it is used more rarely. My bicycle’s attributes
have unique values because my bicycle is green, and not all bicycles are that color.
08 525x ch06 1/24/03 3:35 PM Page 146

×