Creating Conditional Functions


PHP is an interpreted language, which means that functions declared inside conditional statements, such as if statements, can't be called until the PHP interpreter executes that conditional statement and sees those functions. For example, say you have a function like this:

 function existing_function() {   echo "existing_function(): I'm ready to run as soon as the script       starts.<BR>"; } 

That function can be called as soon as your script starts to run:

 existing_function(); 

But what if your function is declared inside an if statement?

 if ($create_function) {     function created_function()     {         echo "created_function(): I'm not ready until the if statement             executes.<BR>";     } } 

In this case, PHP will only be able to find the function after this if statement's body has executedthat is, if the variable $create_function here is trUE. The interpreter will not have seen the function until it executes the if statement's body. So if you want to call the function, make sure that the $create_function variable is TRUE first, like this:

 if ($create_function){     created_function(); } 

You can see all this in a working script in phpconditionalfunction.php, Example 4-13, where we're calling a conditional functionbut only after the if statement containing this function executes.

Example 4-13. Using variable functions, phpconditionalfunction.php
 <HTML>         <HEAD>             <TITLE>                 Creating Conditional Functions             </TITLE>         </HEAD>         <BODY>             <H1>                 Creating Conditional Functions             </H1>             <?php                 function existing_function()                 {                   echo "existing_function(): I'm ready to run as soon as the                         script starts.<BR>";                 }                 existing_function();                 $create_function = TRUE;                 if ($create_function) {                   function created_function()                   {                     echo "created_function(): I'm not ready until the if                           statement executes.<BR>";                   }                 }                 if ($create_function){                     created_function();                 }             ?>     </BODY> </HTML> 

The results appear in Figure 4-13.

Figure 4-13. Using conditional functions.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net