112Part IPHP: The Basicsname to mean the same (Business web hosting)

112Part IPHP: The Basicsname to mean the same thing as it does in the context outside the function. The syntax of thisdeclaration is simply the word global, followed by a comma-delimited list of the variablesthat should be treated that way, with a terminating semicolon. To see the effect, consider anew version of the previous example. The only difference is that we have declared $counttobe global, and we have removed its initial assignment to zero inside the function: function SayMyABCs2 () { global $count; while ($count < 10) { print(chr(ord( A ) + $count)); $count = $count + 1; } print(
Now I know $count letters
); } $count = 0; SayMyABCs2(); $count = $count + 1; print( Now I ve made $count function call(s).
); SayMyABCs2(); $count = $count + 1; print( Now I ve made $count function call(s).
); Our revised version prints the following browser output: ABCDEFGHIJNow I know 10 lettersNow I ve made 11 function call(s). Now I know 11 lettersNow I ve made 12 function call(s). This is buggy behavior, and the globaldeclaration is to blame. There is now only one $countvariable, and it is being increased both inside and outside the function. When the second call toSayMyABCs()happens, $countis already 11, so the loop that prints letters is never entered. Although this example shows globalto bad advantage, it can be quite useful, especiallybecause (as we ll see in Chapter 7) PHP provides some variable bindings to every page evenbefore any of your own code is executed. It can be helpful to have a way for functions to seethese variables without the bother of passing them in as arguments with each call. Static variablesBy default, functions retain no memory of their own execution, and with each function calllocal variables act as though they have been newly created. The staticdeclaration over- rides this behavior for particular variables, causing them to retain their values in betweencalls to the same function. Using this, we can modify our earlier function SayMyABCs2()togive it some memory: function SayMyABCs3 () { static $count = 0; //assignment only if first time called$limit = $count + 10; while ($count < $limit)
If you are looking for affordable and reliable webhost to host and run your business application visit our ftp web hosting services.

Leave a Reply