• No results found

Using Arrays

In document programming PHP pdf (Page 136-141)

Arrays crop up in almost every PHP program. In addition to their obvious use for storing collections of values, they’re also used to implement various abstract data types. In this section, we show how to use arrays to implement sets and stacks.

Using Arrays | 137

Sets

Arrays let you implement the basic operations of set theory: union, intersection, and difference. Each set is represented by an array, and various PHP functions imple- ment the set operations. The values in the set are the values in the array—the keys are not used, but they are generally preserved by the operations.

Theunion of two sets is all the elements from both sets, with duplicates removed. Thearray_merge( )andarray_unique( )functions let you calculate the union. Here’s how to find the union of two arrays:

function array_union($a, $b) {

$union = array_merge($a, $b); // duplicates may still exist $union = array_unique($union);

return $union; }

$first = array(1, 'two', 3);

$second = array('two', 'three', 'four'); $union = array_union($first, $second); print_r($union); Array ( [0] => 1 [1] => two [2] => 3 [4] => three [5] => four )

Theintersectionof two sets is the set of elements they have in common. PHP’s built- inarray_intersect( )function takes any number of arrays as arguments and returns an array of those values that exist in each. If multiple keys have the same value, the first key with that value is preserved.

Another common function to perform on a set of arrays is to get thedifference; that is, the values in one array that are not present in another array. Thearray_diff( )

function calculates this, returning an array with values from the first array that are not present in the second.

The following code takes the difference of two arrays:

$first = array(1, 'two', 3);

$second = array('two', 'three', 'four'); $difference = array_diff($first, $second); print_r($difference); Array ( [0] => 1 [2] => 3 )

Stacks

Although not as common in PHP programs as in other programs, one fairly com- mon data type is the last-in first-out (LIFO) stack. We can create stacks using a pair of PHP functions,array_push( )andarray_pop( ). Thearray_push( )function is iden- tical to an assignment to$array[]. We usearray_push( )because it accentuates the fact that we’re working with stacks, and the parallelism witharray_pop()makes our code easier to read. There are alsoarray_shift( )andarray_unshift( )functions for treating an array like a queue.

Stacks are particularly useful for maintaining state. Example 5-4 provides a simple state debugger that allows you to print out a list of which functions have been called up to this point (i.e., thestack trace).

Example 5-4. State debugger

$call_trace = array( );

function enter_function($name) { global $call_trace;

array_push($call_trace, $name); // same as $call_trace[] = $name

echo "Entering $name (stack is now: " . join(' -> ', $call_trace) . ')<br />'; }

function exit_function( ) { echo 'Exiting<br />'; global $call_trace;

array_pop($call_trace); // we ignore array_pop( )'s return value } function first( ) { enter_function('first'); exit_function( ); } function second( ) { enter_function('second'); first( ); exit_function( ); } function third( ) { enter_function('third'); second( ); first( ); exit_function( ); } first( ); third( );

Using Arrays | 139

Here’s the output from Example 5-4:

Entering first (stack is now: first) Exiting

Entering third (stack is now: third)

Entering second (stack is now: third -> second) Entering first (stack is now: third -> second -> first) Exiting

Exiting

Entering first (stack is now: third -> first) Exiting

Chapter 6

CHAPTER 6

Objects

Object-oriented programming (OOP) opens the door to cleaner designs, easier main- tenance, and greater code reuse. Such is the proven value of OOP that few today would dare to introduce a language that wasn’t object-oriented. PHP supports many useful features of OOP, and this chapter shows you how to use them.

OOP acknowledges the fundamental connection between data and the code that works on that data, and it lets you design and implement programs around that con- nection. For example, a bulletin-board system usually keeps track of many users. In a procedural programming language, each user would be a data structure, and there would probablybe a set of functions that work with users’ data structures (create the new users, get their information, etc.). In an object-oriented programming language, each user would be anobject—a data structure with attached code. The data and the code are still there, but they’re treated as an inseparable unit.

In this hypothetical bulletin-board design, objects can represent not just users, but also messages and threads. A user object has a username and password for that user, and code to identifyall the messages bythat author. A message object knows which thread it belongs to and has code to post a new message, replyto an existing message, and displaymessages. A thread object is a collection of message objects, and it has code to displaya thread index. This is onlyone wayof dividing the neces- saryfunctionalityinto objects, though. For instance, in an alternate design, the code to post a new message lives in the user object, not the message object. Design- ing object-oriented systems is a complex topic, and many books have been written on it. The good news is that however you design your system, you can implement it in PHP.

The object as union of code and data is the modular unit for application develop- ment and code reuse. This chapter shows you how to define, create, and use objects in PHP. It covers basic OO concepts as well as advanced topics such as introspec- tion and serialization.

Creating an Object | 141

In document programming PHP pdf (Page 136-141)