Functions

See the manual on functions for more

PHP's functions are similar to C's. Syntax:

function funcname ($arg_1, $arg_2, ..., $arg_n) {
    statements...
}
See, for example ismcm

Variables can be given default values as in

function makehref($contents,$method="", $tag="") {  
   /* convert $contents to an HTML HREF
      note we wrap $contents with a urlencode
     $method defaults to empty (relative reference)
     $tag is used only if passed
   */
                                 
    if ($tag) {
        return '' . $tag . "";
    } else {
        return '' . $contents . '';
    }}

Variable scope

Variable scope in PHP differs from C and other languages. Within a function all variable references are local, PHP does not inherit variables. Example:
	$a = 5;
	function printa() {
		print "a = $a";
	}
	printa();
		
yields the rather unexpected result:
Notice: Undefined variable: a in /web/html/tutorial/htmlguid/php/function.phtml on line 57
a =

We need to use the global or the $GLOBALS array construct to work around this.

	$a = 5;
	function printa2() {
		global $a;
		print "a = $a<br>";
		print "a = " . $GLOBALS["a"];
	}
	printa2();
		
Giving: a = 5
a = 5

Page Source
<< logic | PHP | Forms