• Aucun résultat trouvé

Upgrading to PHP 5

Dans le document PHP OBJECT-ORIENTED (Page 46-49)

As you’re aware, the major change to PHP with version 5 is improved support for OOP. In this regard, two of the most important changes are the introduc-tion of access modifiers and changed syntax for class construcintroduc-tion. Both of these changes will have an impact on the DirectoryItems class.

Access Modifiers

Next to the concept of a class, access modifiers are arguably the most important feature of an OO language. The principal use of access modifiers is to describe and constrain data members and methods. The access modifiers we are con-cerned with in this chapter are public and private. The modifier private is used to modify or describe matters relating to the internal behavior of a class.

The modifier public is used to describe the external behavior of a class or, if you prefer, a class’s interface.

As far as syntactic changes to the DirectoryItems class are concerned, this means replacing the keyword var with private, so that

var $filearray = array();

becomes

private $filearray = array();

As you’ll recall, $filearray is the sole data member of the DirectoryItems class. In most cases (except static classes, which we will discuss in Chapter 11), you should make all data members private, because by doing so, you are protecting the integrity of your data by restricting access to it.

To better understand access modifiers, it’s useful to think of data members or instance variables as though they are data in a database. In order to maintain the integrity of the data in a database, it’s wise to limit access and restrict the ways in which data can be added or changed. A programmer might well write an application to achieve this result, requiring users to log in and implementing controls on the way in which data are formatted. For instance, you may want dates stored in a particular format and enforce this through the use of a masked textbox.

Since access modifiers are nonexistent in PHP 4, changing the value of a variable only requires a simple assignment. You could modify the

$filearray variable in the following way:

$di->filearray[0] = "anyfile.jpg";

It’s a disadvantage to do things this way because changes to $filearray are not controlled and allowing direct access to data members greatly increases the risk of contaminating your data. If you use the keyword private, direct access is no longer possible.

Mod UR Cla ss 27 NOTE In terms of the preceding database analogy, making an instance variable private

means that access to the data is only permitted through use of the programmer’s application or front end.

But wait, it’s your code, right? You won’t change it improperly, so why should you care? Because OO programming assumes that other programmers may use your objects and vice versa.

Bruce Eckel refers to this as client programmers using objects created by class creators.1Even if you are a lone developer and don’t expect other pro-grammers to use your code, access modifiers are still an important safeguard.

Why? How many times have you returned to your own code, even after only a short period of time away from it, and had trouble trying to figure out what exactly you were trying to achieve? Clearly, in this situation, even though you are the class originator, you are also, at the same time, a client pro-grammer. The use of access modifiers forces the programmer to make his or her intentions explicit. If a particular data member or method relates to the internal behavior of a class, then applying the appropriate access modifier documents this intention. If nothing else, we all need access modifiers to protect our code from that most presumptuous of client programmers—

ourselves.

When first encountering the private keyword, there is sometimes a mis-taken tendency to view it solely as a security measure and then point out its ineffectiveness by showing how easily a malicious user programmer could subvert it. Even more so with a non-compiled language like PHP, because it’s an easy matter to change a modifier from private to public. It’s better to view the use of access modifiers as indicative of the originating program-mer’s intentions—as a form of internal documentation. (However, the use of access modifiers does add to security insofar as any well thought out and well documented class is a more secure class.)

The private keyword can be applied to methods as well as to data members. You’ll see an example of a private method later in this chapter, but for the moment, let’s look at the use of the modifier public when applied to a method.

Once the need for the keyword private is apparent, so also is the need for a public method or interface so that private data members may be accessed in a controlled fashion. Now that the $filearray variable is private, you no longer have any kind of access to it. For this reason, you need a public method, sometimes called an accessor method, in order to retrieve that private variable:

public function getFileArray(){

return $this->filearray }

In the previous chapter, you directly accessed this data member thus:

$di->filearray. You might well wonder what the difference is and conclude that direct access is preferable because it is more succinct. However, the impor-tant difference is that when you directly access a data member, you are working

1 Bruce Eckel, Thinking in Java (Prentice Hall, 1998), 30.

with the original, but when you use a method to retrieve a data member, you retrieve a copy of that original. When working directly with the original, you risk changing its value, inadvertently or otherwise. When working with a copy, there is no such danger because, should the copy be changed, the original will remain intact. In other words, what’s returned from the getFileArray method is returned by value, not by reference. Changing the copy won’t have any effect on the original.

It is perhaps clearer now how a public method is an interface. A public method mediates between a data member and a user programmer in the same way that the front end of a database mediates between a user and the data. Controlled access to the data simplifies how a class is used and, in so doing, helps preserve its integrity.

The Constructor

In Chapter 4, you saw how the class name functioned as a special method called the constructor. However, PHP 5 changes the way that objects are constructed. Specifically,

function DirectoryItems($directory){ ... } becomes

public function __construct($directory){ ... }

Methods beginning with a double underscore are magic methods. They are given this name because they are not (usually) called directly. This new method for constructing objects is invoked in exactly the same way as a con-structor is invoked under PHP 4. Creating an instance of the DirectoryItems class still uses the keyword new along with the class name:

$di = new DirectoryItems("graphics");

The syntax for creating an object is the same, but in PHP 5, the __construct method is executed rather than a method bearing the class name.

NOTE In PHP 5, you need not return the object created by the constructor (or any method for that matter) by reference. The reason for this is explained in Chapter 13 in the section

“__clone” on page 116.

Altering the constructor may seem like an unnecessary change to those of you familiar with constructors in other OO languages, but there are advan-tages that you’ll see when we discuss inheritance. Without getting into the details of inheritance at this early stage, let’s just say that having a fixed name for the constructor in every class allows you to avoid hard-coding class names unnecessarily. This in turn will of course make your code easier to maintain.

NOTE The access modifier public is optional when applied to a constructor (or any other method, for that matter), but it certainly doesn’t hurt to use it. You may still create a constructor using the class name, but adopting the style of PHP 5 now will avoid any future backward-compatibility issues.

Mod UR Cla ss 29

Dans le document PHP OBJECT-ORIENTED (Page 46-49)