Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PHP Programming With MySQL Second Edition.doc
Скачиваний:
0
Добавлен:
01.05.2025
Размер:
43.07 Mб
Скачать

CHAPTER 10

Developing Object-Oriented PHP

574

members of different data types, so calling a class a data type becomes

even more confusing. One reason classes are called user-defined data

types or programmer-defined data types is that you can work with a

class as a single unit, or object, in the same way you work with a vari-

able. In fact, the terms “variable” and “object” are often used inter-

changeably in object-oriented programming. The term “object-oriented

programming” comes from the fact that you can bundle variables and

functions together and use the result as a single unit (a variable or

object).

This information will become clearer to you as you progress through

this chapter. For now, think of the handheld calculator example. A

calculator could be considered an object of a Calculation class. You

access all of the Calculation class functions (such as addition and

subtraction) and its data members (operands that represent the num-

bers you are calculating) through your calculator object. You never

actually work with the Calculation class yourself, only with an object

of the class (your calculator).

But why do you need to work with a collection of related variables

and functions as a single object? Why not simply call each individual

Variable and function as necessary, without bothering with all this

class business? The truth is, you are not required to work with classes;

you can create much of the same functionality without classes as you

can by using classes. In fact, many of the scripts that you create—and

that you find in use today—do not require object-oriented techniques

to be effective. Classes help make complex programs easier to man-

age, however, by logically grouping related functions and data and

by allowing you to refer to that grouping as a single object. Another

reason for using classes is to hide information that users of a class do

not need to access or know about; this helps minimize the amount of

information that needs to pass in and out of an object. Classes also

make it much easier to reuse code or distribute your code to others

for use in their programs. (You will learn how to create your own

classes and include them in your scripts shortly.) Packaging related

variables and functions into a class is similar to packaging them into a

single include file, then using the include() statement to insert them

in a PHP script. The difference is that an include file can only contain

a single copy of each variable, whereas each instance of a class will

contain a distinct copy of each variable.

Another reason to use classes is that instances of objects inherit their

characteristics, such as class members, from the class upon which

they are based. This inheritance allows you to build new classes based

on existing classes without having to rewrite the code contained in

the existing classes.

Using Objects in PHP Scripts

Creating a Class Definition

To create a class in PHP, you use the class keyword to write a class

definition, which contains the data members and member functions

that make up the class. The basic syntax for defining a class is as follows:

class ClassName {

data member and member function definitions

}

575

The ClassName portion of the class definition is the name of the new

class. You can use any name you want for a structure, as long as you

follow the same naming conventions that you use when declaring

other identifiers, such as variables and functions. Also, keep in mind

that class names usually begin with an uppercase letter to distinguish

them from other identifiers. Within the class’s curly braces, you

declare the data type and field names for each piece of information

stored in the structure, the same way you declare data members and

member functions that make up the class.

The following code demonstrates how to declare a class named

BankAccount. The statement following the class definition instantiates

an object of the class named $Checking.

class BankAccount {

data member and member function definitions

}

$Checking = new BankAccount();

Class names

In a class

definition are

not followed

by parenthe-

ses, as function names

are in a function

definition.

Because the BankAccount class does not yet contain any data mem-

bers or member functions, there isn’t much you can do with the

$Checking object. However, PHP includes a number of built-in

functions that you can use to return information about the class

that instantiated the object. For example, the get_class() function

returns the name of the class that instantiated the object. You pass the

name of the object to the get_class() function, as follows:

$Checking = new BankAccount();

echo 'The $Checking object is instantiated from the '

. get_class($Checking) . " class.</p>\n";

See the

Class/Object

Functions

reference in

the online PHP

documentation at http://

www.php.net/docs.php

for more information on

the functions you can use

with classes and objects.

You can also use the instanceof comparison operator to deter-

mine whether an object is instantiated from a given class. The syn-

tax for using the instanceof operator is object_name instanceof

class_name. For example, the following code uses an if statement

and the instanceof operator to determine whether the $Checking

object is an instance of the BankAccount class:

$Checking = new BankAccount();

if ($Checking instanceof BankAccount)

echo "The \$Checking object is instantiated from the

BankAccount class.</p>\n";


CHAPTER 10

Developing Object-Oriented PHP

576

One built-in class function that you should use whenever you declare

an object is the class_exists() function, which determines whether

a class exists and is available to the current script. You pass to the

class_exists() function a string value containing the name of the

class you want to use. The function returns a value of TRUE if the class

exists and FALSE if it doesn’t. For example, the following code uses

the class_exists() function within an if statement’s conditional

expression to check for the existence of the BankAccount class. If the

class exists, the $Checking object is instantiated. If the class does not

exist, the else clause displays an error message.

if (class_exists("BankAccount"))

$Checking = new BankAccount();

else

echo "<p>The BankAccount class is not available!</p>\n";

Storing Classes in External Files

Just as you

preface the

names of

include files

with “inc_” to

easily distinguish them

from regular PHP files,

you can preface the

name of class files with

“class_”, as in “class_

BankAccount.php”.

Although you can define a class within the same document that

instantiates an object of the class, this somewhat defeats the purpose

of writing code that can be easily modified and reused. If you want

to reuse the class, you need to copy and paste it between scripts.

Further, if you want to modify the class, you need to modify it

within every script that uses it. A better solution is to define a class

within a single external file that is called from each script that needs

the class, using the include(), include_once(), require(), and

require_once() functions that you learned in Chapter 2.

To start creating the OnlineStore class and using it in

GosselinGourmetCoffee.php:

1.

Create a new document in your text editor and add a PHP

script section, as follows:

<?php

?>

2.

Add the following class definition for the OnlineStore class

to the script section:

class OnlineStore {

}

3.

Save the document as class_OnlineStore.php in the Chapter

directory for Chapter 10.

Return to the GosselinGourmetCoffee.php script in your

text editor.

Add the following statement to the PHP script section at the

beginning of the file, beneath the require_once() statement

for inc_OnlineStoreDB.php. This statement uses another

4.

5.


Using Objects in PHP Scripts

require_once() statement that makes the OnlineStore class

available to the GosselinGourmetCoffee.php script.

require_once("class_OnlineStore.php");

6.

Add the following statements beneath the statement that

includes the OnlineStore class file. These statements instanti-

ate an object of the OnlineStore class.

if (class_exists("OnlineStore")) {

$Store = new OnlineStore();

}

else {

$ErrorMsgs[] = "The OnlineStore class is not

available!";

$Store = NULL;

}

577

7.

Add the following statements to the start of the PHP script

section in the body of the document, immediately before the

if statement that queries the database:

if ($Store !== NULL)

echo "<p>Successfully instantiated an object of " .

" the OnlineStore class.</p>\n";

8.

Save the GosselinGourmetCoffee.php script and then upload

both documents to the Web server.

Open the GosselinGourmetCoffee.php script in your Web

browser by entering the following URL: http://<yourserver>/

PHP_Projects/Chapter.10/Chapter/GosselinGourmetCoffee.

php. You should see the message shown in Figure 10-6.

9.

Figure 10-6

10.

Gosselin’s Gourmet Coffee Web page after instantiating an OnlineStore object

Close your Web browser window.


CHAPTER 10

Developing Object-Oriented PHP

Collecting Garbage

If you have worked with other object-oriented programming lan-

guages, you might be familiar with the term garbage collection,

which refers to cleaning up, or reclaiming, memory that is reserved

by a program. When you declare a variable or instantiate a new

object, you are actually reserving computer memory for the vari-

able or object. With some programming languages, you must write

code that deletes a variable or object after you finish with it. This

frees the memory for use by other parts of your program or by other

programs running on your computer. With PHP, you do not need to

worry about reclaiming memory that is reserved for your variables or

objects. Although you can manually remove a variable or object with

the unset() function, there is usually no reason to do so—as with

variables, PHP will automatically clean up unused memory when

an object within a function goes out of scope, or at the end of the

script for global objects. The one exception involves open database

connections. As you learned in Chapter 8, because database con-

nections can take up a lot of memory, you should explicitly close a

database connection when you finish with it by calling the procedural

mysql_close() function or the close() method of the mysqli class.

This ensures that the connection doesn’t keep taking up space in your

computer’s memory while the script finishes processing.

578

Short Quiz

1.

2.

Illustrate the syntax of instantiating an object.

What operator is used to access the methods and properties

contained in an object?

What function of the mysqli object is used to determine if a

database connection failed?

Illustrate the syntax used to define a PHP class.

Explain the term “garbage collection.”

3.

4.

5.

Declaring Data Members

In this section, you will learn how to declare data members within a

class. Declaring and initializing data members is a little more involved

than declaring and initializing standard PHP variables. To be able

to declare data members, you must first understand the principle of

information hiding, which you will study first.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]