TAILIEUCHUNG - OBJECT-ORIENTED PHP Concepts, Techniques, and Code- P15

OBJECT-ORIENTED PHP Concepts, Techniques, and Code- P15:A number of years ago, before I started using PHP, I created dynamic web pages using C. This really wasn’t too different from some of the other options available at the time, though it seems almost unthinkable now. Creating a dynamic page meant outputting HTML from your script and recompiling that script if any changes needed to be made. | While looping through the array of players O each individual player is cloned and added to a new array. Doing this creates a separate array for the cloned team. After making these changes running the code in Listing 13-6 now yields this output Rovers Array 0 Player Object name private Roy position private Omidfielder Reserves Array 0 Player Object name private Roy position private striker Changing a player originally added to the rovers has no effect on the player array in O the cloned reserves object. This is the result you want. The magic clone method allows you to define what happens when an object is cloned. Using the terminology of other OO languages the_clone method is a copy constructor. It s up to the developer to decide what s appropriate for any particular class but as a general rule a_clone method should always be defined for aggregate classes for the exact reasons shown in the sample code normally the same variable isn t shared among different instances of a class. That s what static data members are for. A Get Method for Object Data Members of an Aggregate Class When I first introduced accessor methods in Chapter 5 I noted that one of the advantages of a get method over direct access to a public data member was that accessor methods return a copy rather than an original. This is not true when the data members are themselves objects by default objects are returned by reference. In the interests of data protection it is usually better to return a copy using the clone operator. With this in mind let s rewrite the getPlayers method originally shown in Listing 13-5 shown here in Listing 13-8. public function getPlayers arraycopy array foreach this- players as p arraycopy clone p return arraycopy Listing 13-8 Returning a copy of an object The array returned by this version of the getPlayers method is only a copy so changes made to it will have no effect on the data member players. If you need to make changes to the players array a set method will have to be

TỪ KHÓA LIÊN QUAN
TÀI LIỆU HOT