Returning to the Petals GameAt the beginning of
September 29, 2006 on 11:20 am | In php | No Comments
Petals Around the Rose
I decided on a tan background with a whimsical font. This should give the programa light feel. Main Body CodeThe main PHP code segment has three main jobs: print a greeting, print the dice, and print the form for the next turn. These jobs are (appropriately enough) stored in three different functions. One goal of encapsulation is to make themain code body as clean as possible. This goal is achieved in the Petalsgame. printGreeting(); printDice(); printForm(); All the real work is passed off to the various functions, which are describedshortly. Even before you see the functions themselves, you have a good idea whateach function does and a good sense of the program s overall flow. Encapsulat- ing your code and naming your functions well makes your code much easier toread and repair. The printGreeting() FunctionThe printGreeting()function prints one of three possible greetings to the user. If the user has never called this program before, the program should provide awelcome. If the user has been here before, she has guessed the number of petals. That guess might be correct (in which case a congratulatory message is appro- priate) or incorrect, requiring information about what the correct answer was. The printGreeting()function uses a switchstatement to handle the variousoptions. function printGreeting(){ global $guess, $numPetals; if (empty($guess)){ print
Welcome to Petals Around the Rose
;
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services
Returning to the Petals GameAt the beginning of
September 29, 2006 on 11:20 am | In php | No CommentsReturning to the Petals GameAt the beginning of this chapter I show you the Petals Around the Rosegame. This game uses all the skills you have learned so far, including the new conceptsfrom this chapter. If you haven t already done so, play the game now so you cansee how it works. Here s the basic plan of the Petalsgame: Each time the page is drawn, it randomlygenerates five dice and calculates the correct number of petals based on a super- secret formula. The page includes a form that has a text area called guessfor theuser to enter the answer. The form also includes a hidden field called numPetals, which tells the program what the correct answer was. The Petalsgame doesn t introduce anything new, but it s a little longer than anyof the other programs you ve seen so far. I introduce the code in smaller chunks. All the code is shown in order, but not in one long code sample. Look on the CDfor the program in its entirety. Starting HTMLLike most PHP programs, the Petalsgame uses some HTML to set everything up. The HTML is pretty basic because PHP code creates most of the interesting HTML.
88PHP5/MySQLProgrammingfortheAbsoluteBeginnerCAN TTHEPROGRAMREMEMBERTHERIGHTANSWER? Since the program generated the correct answer in the first place, you might besurprised to learn that the right answer must be hidden in the Web page andthen retrieved by the same program that generated it. Each contact betweenthe client and the server is completely new. When the user first plays the game, the page is sent to the browser and the con- nection is completely severed until the user hits the submitbutton. When theuser submits the form, the Petalsprogram starts over again. It s possible theuser plays the game right before he goes to bed, then leaves the page on thecomputer overnight. Meanwhile, a hundred other people might use the pro- gram. For now, use hidden data to help keep track of the user s situation. Laterin this book you learn some other clever methods for keeping track of the users situations.Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services
ControllingYourCodewithConditionsandFunctionscase 4: $place = door ; break; default: $place
September 29, 2006 on 7:08 am | In php | No Commentswhen you want a function to use a variable created at the main level. These program- level variables are also called globalvariables. If you ve programmed in another language, you re bound to get confused by the wayPHP handles global variables. In most languages, any variable created at the mainlevel is automatically available to every function. In PHP, you must explicitlyrequest that a variable be global inside a function. If you don t do this, a new localvariable with the same name (and no value) is created at the function level. Looking at the Scope DemoTo illustrate the notion of global variables, take a look at the Scope Demo, shownin Figure 3.16. Take a look at the code for the Scope Demoand see how it works:
Scope Demo
Demonstrates variable scope
TRAP86PHP5/MySQLProgrammingfortheAbsoluteBeginnerFIGURE 3.16Variable $akeepsits value inside afunction, but $bdoes not.
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services
ControllingYourCodewithConditionsandFunctionscase 4: $place = door ; break; default: $place
September 29, 2006 on 7:08 am | In php | No CommentsControllingYourCodewithConditionsandFunctions $a = I have a value ; $b = I have a value ; print <<
\$b is $b
HERE; myFunction(); function myFunction(){ //make $a global, but not $bglobal $a; print <<
\$b is $b
HERE; } // end myFunction?> I created two variables for this demonstration: $aand $b. I gave them both thevalue I have a value. As a test, I printed out the values for both $aand $b. Notice the trick I used to make the actual dollar sign show up in the quotationmarks. When PHP sees a dollar sign inside quotation marks, it usually expects tobe working with a variable. Sometimes (as in this case) you really want to print adollar sign. You can precede a dollar sign with a backslash to have the signappear. So, print $aprints the value of the variable $a, but print \$aprintsthe value $a . TRICK
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services
ControllingYourCodewithConditionsandFunctionscase 4: $place = door ; break; default: $place
September 29, 2006 on 7:08 am | In php | No CommentsControllingYourCodewithConditionsandFunctionscase 4: $place = door ; break; default: $place = I don t know where ; } // end switch$output = <<
HERE; return $output; } // end verseIn this function, I indicated $stanza as a parameter in the function definition. Aparameter is simply a variable associated with the function. If you create a functionwith a parameter, you are required to supply some sort of value whenever you callthe function. The parameter variable automatically receives the value from the mainbody. For example, if the program says verse(1), the versefunction is called and the$stanzavariable contains the value 1. I then used a switchstatement to populate the$placevariable based on the value of $stanza. Finally, I created the $outputvariableusing the $stanzaand $placevariables and returned the value of $output. You can create functions with multiple parameters. Simply declare several variables inside the parentheses of the function definition, and be sure to call thefunction with the appropriate number of arguments. Make sure to separate para- meters with commas. Managing Variable ScopeYou have learned some ways to have your main program share variable informa- tion with your functions. In addition to parameter passing, sometimes you wantyour functions to have access to variables created in the main program. This isespecially true because all the variables automatically created by PHP (such asthose coming from forms) are generated at the main level. You must tell PHPTRICKINTHEREALWORLDIf you re an experienced programmer, you probably know other ways to makethis code even more efficient. You return to this program as you learn aboutloops and arrays in the coming chapters.
Note: If you are looking for inexpensive but high quality provider to host and run your jsp application check Astra jsp hosting services
case 3: $place = knee ; break; case 4:
September 29, 2006 on 3:06 am | In php | No Commentsprint verse(3); print chorus(); print verse(4); print chorus(); The program is to print the first verse, then the chorus, then the second verse, then the chorus, and so on. The details of how all these things are to be gener- ated is left to the individual functions. This is an example of encapsulation. Encapsulation is good, because it allows you to think about problems in multiplelevels. At the highest level, you re interested in the main ideas (print the versesand chorus) but you re not so concerned about the exact details. You use thesame technique when you talk about your day: I drove to work, had some meet- ings, went to lunch, and taught a class. You don t usually describe each detail ofeach task. Each major task can be broken down into its component tasks later. (Ifsomebody asks, you could really describe the meeting: I got some coffee, appeared to be taking notes furiously on my PDA, got a new high score on Solitairewhile appearing to take notes, scribbled on the agenda, and dozed off during apresentation. ) Returning a Value: The chorus() FunctionAnother interesting thing about the code s main section code is the use of theprint()function. In the last program, I simply said chorus()and the programprinted the verse. In this program, I did it a little differently. The chorus()func- tion doesn t actually print anything to the screen. Instead, it creates the chorusas a big string and sends that value back to the program, which can do whateverit wants with it. This behavior isn t new to you. Think about the rand()function. It always returnsa value to the program. The functions in this program work the same way. Takeanother look at the chorus()function to see what I mean: function chorus(){ $output = <<
give a dog a bone
this old man came rolling home
HERE; return $output; } // end chorus83Chapter3
Note: If you are looking for high quality webhost to host and run your jsp application check Vision jsp hosting services
case 3: $place = knee ; break; case 4:
September 29, 2006 on 3:06 am | In php | No CommentsI began the function by creating a new variable called $output. You can createvariables inside functions by mentioning them, just like you can in the main partof the program. However, a variable created inside a function loses its meaningas soon as the function is finished. This is good, because it means the variablesinside a function belong only to that function. You don t have to worry aboutwhether the variable already exists somewhere else in your program. You alsodon t have to worry about all the various things that can go wrong if you mis- takenly modify an existing variable. I assigned a long string (the actual chorus ofthe song) to the $outputvariable with the <<
case 3: $place = knee ; break; case 4:
September 29, 2006 on 3:06 am | In php | No Commentscase 3: $place = knee ; break; case 4: $place = door ; break; default: $place = I don t know where ; } // end switch$output = <<
HERE; return $output; } // end versefunction chorus(){ $output = <<
give a dog a bone
this old man came rolling home
HERE; return $output; } // end chorus?> Looking at Encapsulation in the Main Code BodyThis code features a number of improvements over the previous version. Firstlook at the main body of the code, which looks like this: print verse(1); print chorus(); print verse(2); print chorus(); 82PHP5/MySQLProgrammingfortheAbsoluteBeginner
Note: If you are looking for high quality webhost to host and run your jsp application check Vision jsp hosting services
This old man, he played 2 He played
September 28, 2006 on 11:22 pm | In php | No CommentsControllingYourCodewithConditionsandFunctions
Param Old Man
Demonstrates use of function parameters
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; FIGURE 3.15While the outputlooks similar toFigure 3.14, theprogram thatproduced this pageis much moreefficient.
Note: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services
This old man, he played 2 He played
September 28, 2006 on 11:22 pm | In php | No Comments80PHP5/MySQLProgrammingfortheAbsoluteBeginnerWhen you look at my code, you note there s one line I never indent: the HEREtokenused for multi-line strings. The word HEREacts like a closing quotation mark andmust be all the way to the left side of the screen, so it can t be indented. You can use any function name you like. Careful, though: If you try to define a function that already exists, you re bound to get confused. PHP has a large numberof functions already built in. If you re having strange problems with a function, look at the Help to see if that function already exists. The chorus()function is especially handy in this program because it can bereused. It isn t necessary to rewrite the code for the chorus each time, when youcan simply call a function instead. Using Parameters and Function ValuesFunctions are meant to be self-contained. This is good because the entire programcan be too complex to understand. If you break the complex program into smallerfunctions, each function can be set up to work independently. When you workinside a function, you don t have to worry about anything outside the function. Ifyou create a variable inside a function, that variable dies as soon as you leave thefunction. This prevents many errors that can otherwise creep into your code. The bad side of functions being so self-contained is evident when you want themto work with data from the outside. You can accomplish this a couple of ways. Send a parameterto a function, which allows you to determine one ormore values sent to the function as it starts. Give a function a returnvalue. The paramprogram shown in Figure 3.15 illustrates another form of the This OldMan song. Although again the user might be unaware, some important differencesexist between this more sophisticated program and the first This Old Manprogram. Examining the Param.php ProgramNotice that the output of Figure 3.15 is longer than that of 3.14, but the code thatgenerates this longer output is shorter.
TRAPTRICKNote: If you are looking for reliable and quality webspace company to host and run your servlet application check Actions servlet hosting services
Powered by cheap hosting