Page 186 - Beginning PHP 5.3
P. 186
Part II: Learning the Language
In other words, you insert the parameter name, followed by an equals ( = ) sign, followed by a default
value. This is the value that the parameter will take on if the corresponding argument is not passed
when the function is called. So you could then rewrite the previous hello_with_style.php script
as follows:
< !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
< html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
< head >
< title > Saying hello with style < /title >
< link rel=”stylesheet” type=”text/css” href=”common.css” / >
< /head >
< body >
< h1 > Saying hello with style < /h1 >
< ?php
function helloWithStyle( $font, $size=1.5 ) {
echo “ < p style=\”font-family: $font; font-size: {$size}em;\” > Hello, world! < /p > ”;
}
helloWithStyle( “Helvetica”, 2 );
helloWithStyle( “Times”, 3 );
helloWithStyle( “Courier” );
? >
< /body
>
< /html >
You can see that the third call to helloWithStyle() doesn ’ t pass a second argument to the function.
This causes PHP to give the $size parameter its default value of 1.5. The end result is that the third
“ Hello, world! ” is displayed in Courier font with a size of 1.5 em, just like the first version of the script.
Returning Values from Your Functions
Earlier in the chapter, you saw that functions can return values as well as accept them. For example, the
built - in sqrt() function shown earlier accepts an argument (a number) and returns a value (the square
root of that number).
Note that both accepting arguments and returning values are optional. A function can do either, both, or
neither of these things.
To get your function to return a value, you use — you guessed it — PHP ’ s return statement:
function myFunc() {
// (do stuff here)
return value;
}
value can be any expression, so you can use a literal value (such as 1 or false ), a variable name (such
as $result ), or a more complex expression (for example, $x * 3 / 7 ).
148
9/21/09 9:00:53 AM
c07.indd 148 9/21/09 9:00:53 AM
c07.indd 148