05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Stacks<br />

Although not as common in <strong>PHP</strong> programs as in other programs, one fairly common<br />

data type is the last-in first-out (LIFO) stack. We can create stacks using a pair<br />

of <strong>PHP</strong> functions, array_push( ) and array_pop( ). The array_push( ) function is identical<br />

to an assignment to $array[]. We use array_push( ) because it accentuates the<br />

fact that we’re working with stacks, and the parallelism with array_pop() makes our<br />

code easier to read. There are also array_shift( ) and array_unshift( ) functions for<br />

treating an array like a queue.<br />

Stacks are particularly useful for maintaining state. Example 5-4 provides a simple<br />

state debugger that allows you to print out a list of which functions have been called<br />

up to this point (i.e., the stack trace).<br />

Example 5-4. State debugger<br />

$call_trace = array( );<br />

function enter_function($name) {<br />

global $call_trace;<br />

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

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

}<br />

function exit_function( ) {<br />

echo 'Exiting';<br />

global $call_trace;<br />

array_pop($call_trace); // we ignore array_pop( )'s return value<br />

}<br />

function first( ) {<br />

enter_function('first');<br />

exit_function( );<br />

}<br />

function second( ) {<br />

enter_function('second');<br />

first( );<br />

exit_function( );<br />

}<br />

function third( ) {<br />

enter_function('third');<br />

second( );<br />

first( );<br />

exit_function( );<br />

}<br />

first( );<br />

third( );<br />

138 | Chapter 5: Arrays<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!