|
home—lects—exams—hws
breeze (snow day)
From PHP Visual Quickstart Guide by Larry Ullman
Based on notes by Jack Davis (jcdavis@radford.edu)
Creating functions can save you oodles of time over the course of your programming projects. They are needed if you want to create well structured Web applications. You should use functions to modularize code and to build reusable code. You are encouraged to make a file for the reusable parts of data verification, as well as a file of for common utility functions, and include these functions from other files.
function whatever() { print 'whatever'; }
function whatever() { print ("Hello"); return "abc"; }
Variables defined within a function exist only within the function,
as you'd expect.
Non-standard:
However, variables declared outside the function -- at the file's top-level --
are not in scope in your function!,
unless you explicitly "import" them with the keyword
function whatever() { global $a; // We are using $a taken from the enclosing context. $a = $a+1; … } |
Minimize the use of global variables.
Consider passing in information the function needs as a parameter,
rather than use a global variable.
(That's the whole reason parameters were invented!)
The reason for this non-standard scoping behavior?
Here's my guess:
in a web-scripting language, it's common to scrape code from
other people's pages w/o fully understanding how it works.
If you see the keyword
function swap(&$a, &$b) { // Any changes made to $a will be // reflected back in the calling program $tmp = $a; $a = $b; $b = $tmp; } |
home—lects—exams—hws
breeze (snow day)
©2011, Ian Barland, Radford University Last modified 2011.Mar.13 (Sun) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |