05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

$counter = 10;<br />

update_counter( );<br />

echo $counter;<br />

10<br />

The $counter inside the function is local to that function, because we haven’t said<br />

otherwise. The function increments its private $counter, whose value is thrown away<br />

when the subroutine ends. The global $counter remains set at 10.<br />

Only functions can provide local scope. Unlike in other languages, in <strong>PHP</strong> you can’t<br />

create a variable whose scope is a loop, conditional branch, or other type of block.<br />

Global scope<br />

Variables declared outside a function are global. That is, they can be accessed from<br />

any part of the program. However, by default, they are not available inside functions.<br />

To allow a function to access a global variable, you can use the global keyword<br />

inside the function to declare the variable within the function. Here’s how we<br />

can rewrite the update_counter( ) function to allow it to access the global $counter<br />

variable:<br />

function update_counter ( ) {<br />

global $counter;<br />

$counter++;<br />

}<br />

$counter = 10;<br />

update_counter( );<br />

echo $counter;<br />

11<br />

A more cumbersome way to update the global variable is to use <strong>PHP</strong>’s $GLOBALS array<br />

instead of accessing the variable directly:<br />

function update_counter ( ) {<br />

$GLOBALS[counter]++;<br />

}<br />

$counter = 10;<br />

update_counter( );<br />

echo $counter;<br />

11<br />

Static variables<br />

A static variable retains its value between calls to a function but is visible only within<br />

that function. You declare a variable static with the static keyword. For example:<br />

function update_counter ( ) {<br />

static $counter = 0;<br />

$counter++;<br />

echo "Static counter is now $counter\n";<br />

}<br />

$counter = 10;<br />

32 | Chapter 2: Language Basics<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!