PDA

View Full Version : function parameters



gilbertsavier
13 Jul 2009, 11:54 PM
Hi,
In the code below, I understand the $place variable and how it's working. What I can't understand is how I'M getting the output "he played 1, 2, etc... How is that function and the $stanza variable returning a single digit number? Thanks
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Param Old Man</title>
</head>

<body>

<h1>Param Old Man</h1>
<h3>Demonstrates use of function parameters</h3>
<?php

print verse(1);
print chorus();
print verse(2);
print chorus();
print verse(3);
print chorus();
print verse(4);
print chorus();

function verse($stanza)
{
switch($stanza)
{
case 1:
$place = "thumb";
break;
case 2:
$place = "shoe";
break;
case 3:
$place = "knee";
break;
case 4:
$place = "door";
break;
default:
$place = "I don't know where";
} //end switch

$output = <<<HERE
This old man, he played $stanza<br>
He played knick-knack on my $place<br><br>
HERE;
return $output;
} //end veruse

function chorus()
{
$output = <<<HERE
...with a knick-knack<br>
paddy-wack<br>
give a dog a bone<br>
this old man came rolling home<br>
<br><br>
HERE;
return $output;
}// end chorus

?>
</body>
</html>

--------------------------
Thanks & regards
Lokananth
Live chat (http://www.mioot.com) By miOOt

hpwebsolutions
14 Jul 2009, 12:25 AM
First PHP calls the verse function. The verse() function then starts from the top of the function in the switch statement. Every time it sees the word 'case' it compares the value of $stanza to the value of the 'case'. Since the first time verse is called the value of $stanza is 1, the first 'case' matches $stanza and the code within the 'case' is executed. That code assigns the value of "thumb" to $place, and $place is now a variable that will only have tha value within the verse function. PHP then sees the keyword 'break' which terminates the switch statement and puts the program pointer at the first line after the switch statement. If that keyword 'break' wasn't there, PHP would have checked the next case instead of jumping out of the switch statement. After the switch statement, we come to some PHP 'heredoc'. Within the 'heredoc', $stanze and $place are substituted with their actual values (this is technically called "string parsing"). $output is then assigned the value of the entire 'heredoc' string. Then verse() returns the value of $output. So really in the end, the verse() function isn't returning a single digit string but the entire string generated by the 'heredoc'.