-2

我试图看看我是否可以让这个函数检查它是否已经在它被调用两次时运行。基本上它首先显示状态描述,再次调用 display_form 函数,在底部弹出一个表单供用户选择特定城市,我想显示所选城市的描述。我现在很困惑。

这是我的代码:

    <body>


        <h1>State and City Description</h1>
        <?php

            function display_form()
            {
                $stateArray = array('Pennsylvania'=>'Pennsylvania', 'California'=>'California', 'Florida'=>'Florida', 'Colorado'=>'Colorado', 'Texas'=>'Texas');
                $cityPA_Array = array('a'=>'Philadelphia', 'b'=>'Harrisburg', 'c'=>'Pittsburgh');
                $cityCA_Array = array('a'=>'San Francisco', 'b'=>'Los Angeles', 'c'=>'San Diego');
                $cityFL_Array = array('a'=>'Miami', 'b'=>'Naples', 'c'=>'Orlando');
                $cityCO_Array = array('a'=>'Boulder', 'b'=>'Auora', 'c'=>'Colorado Springs');
                $cityTX_Array = array('a'=>'Houston', 'b'=>'Dallas', 'c'=>'Austin');

                if($var == 0) {
                $form = '<form action="testsad.php" method="post">';
                $form .= '<table>';
                $form .= '<tr><td style="width:150px;">Name:</td>'.
                         '<td style="width:150px;"><input type="text" name="formName" /></td></tr>';
                $form .= '<tr><td>Select a state to visit:</td><td>
                          <select name=\'stateName\'>';

                foreach ($stateArray as $stateAbbrev => $stateName) {
                $form .= '<option value="'.$stateAbbrev.'">'.$stateName.'</option>';
                         }//end foreach loop
                $form .= '<tr><td style="text-align:center;"><input type="submit" value="Submit" /></td></tr>';

                $form .= '</select>
                          </td></tr>
                          </form><p></p>';
                $var = 1;
                }//end if statement
                elseif($GLOBALS['first'] == 1) {

                     if($stateName =='Pennsylvania') {
                        $form = '<form action="testsad.php" method="post">';
                        $form .= '<table>';
                        $form .= '<tr><td>Select a city to visit:</td><td>
                                 <select name=\'cityName\'>';

                                foreach ($cityPA_Array as $cityChoice => $cityName) {
                        $form .= '<option value="'.$cityChoice.'">'.$cityName.'</option>';
                                }//end foreach loop
                        $form .= '<tr><td style="text-align:center;"><input type="submit" value="Submit" /></td></tr>';

                        $form .= '</select>
                                 </td></tr>
                                 </form><p></p>';
                     }//end if
                        elseif($stateName =='California') {
                        $form = '<form action="testsad.php" method="post">';
                        $form .= '<table>';
                        $form .= '<tr><td>Select a city to visit:</td><td>
                                 <select name=\'cityName\'>';

                                foreach ($cityCA_Array as $cityChoice => $cityName) {
                        $form .= '<option value="'.$cityChoice.'">'.$cityName.'</option>';
                                }//end foreach loop
                        $form .= '<tr><td style="text-align:center;"><input type="submit" value="Submit" /></td></tr>';

                        $form .= '</select>
                                 </td></tr>
                                 </form><p></p>';
                     }//end elseif                         
                        elseif($stateName =='Florida') {
                        $form = '<form action="testsad.php" method="post">';
                        $form .= '<table>';
                        $form .= '<tr><td>Select a city to visit:</td><td>
                                 <select name=\'cityName\'>';

                                foreach ($cityFL_Array as $cityChoice => $cityName) {
                        $form .= '<option value="'.$cityChoice.'">'.$cityName.'</option>';
                                }//end foreach loop
                        $form .= '<tr><td style="text-align:center;"><input type="submit" value="Submit" /></td></tr>';

                        $form .= '</select>
                                 </td></tr>
                                 </form><p></p>';
                     }//end elseif                            
                        elseif($stateName =='Texas') {
                        $form = '<form action="testsad.php" method="post">';
                        $form .= '<table>';
                        $form .= '<tr><td>Select a city to visit:</td><td>
                                 <select name=\'cityName\'>';

                                foreach ($cityTX_Array as $cityChoice => $cityName) {
                        $form .= '<option value="'.$cityChoice.'">'.$cityName.'</option>';
                                }//end foreach loop
                        $form .= '<tr><td style="text-align:center;"><input type="submit" value="Submit" /></td></tr>';

                        $form .= '</select>
                                 </td></tr>
                                 </form><p></p>';
                     }//end elseif    
                        elseif($stateName =='Colorado') {
                        $form = '<form action="testsad.php" method="post">';
                        $form .= '<table>';
                        $form .= '<tr><td>Select a city to visit:</td><td>
                                 <select name=\'cityName\'>';

                                foreach ($cityCO_Array as $cityChoice => $cityName) {
                        $form .= '<option value="'.$cityChoice.'">'.$cityName.'</option>';
                                }//end foreach loop
                        $form .= '<tr><td style="text-align:center;"><input type="submit" value="Submit" /></td></tr>';

                        $form .= '</select>
                                 </td></tr>
                                 </form><p></p>';
                     }//end elseif                                         
                     $var = 0;
                }//end else statement

                return $form;
            }//end display_form()

            function display($state)
            {
                $analyze = '<h1>';
                if ($state['stateName'] == 'Pennsylvania') {

                    $analyze .= '<tr><th>'.$state['formName'].', here is info for: '.$state['stateName'].'</th></tr>';  


                    $analyze .= '<p>Pennsylvania is a wonderful state! It is a part of the appalachian mountains and has many traditions.<br/><br/> The new state Capitol drew rave reviews. Its dome was inspired by the domes of St. Peter\'s Basilica in Rome and the United States Capitol. President Theodore Roosevelt called it "the most beautiful state Capital in the nation" and said, "Its the handsomest building I ever saw" at the dedication. In 1989, the New York Times praised it as "grand, even awesome at moments, but it is also a working building, accessible to citizens ... a building that connects with the reality of daily life".<br/><br/>
                    Pennsylvania accounts for nine percent of wooded areas in the United States. In 1923 President Calvin Coolidge established the Allegheny National Forest under the authority of the Weeks Act of 1911 in the northwest part of the state in Elk, Forest, McKean, and Warren Counties for the purposes of timber production and watershed protection in the Allegheny River basin. The Allegheny is the state\'s only national forest.
                    <br/>James Buchanan, of Franklin County, the only bachelor President of the United States, was the only one to be born in Pennsylvania. The Battle of Gettysburg, the major turning point of the Civil War—took place near Gettysburg. An estimated 350,000 Pennsylvanians served in the Union Army forces along with 8,600 African American military volunteers.
                    Pennsylvania was also the home of the first commercially drilled oil well. In 1859, near Titusville, Pennsylvania, Edwin L. Drake successfully drilled the well, which led to the first major oil boom in United States history.</p>';  
                }//end if
                if ($state['stateName'] == 'California') {

                    $analyze .= '<tr><th>'.$state['formName'].', here is info for: '.$state['stateName'].'</th></tr>';  


                    $analyze .= '<p>California\'s Mount Whitney measures as the highest peak in the lower 48 states. Its most famous climb is Mount Whitney Trail to the 14,495 feet summit. Wilderness permits are required.
                                 In 1925 a giant sequoia located in California\'s Kings Canyon National Park was named the nation\'s national Christmas tree. The tree is over 300 feet in height.
                                 More turkeys are raised in California than in any other state in the United States.</p>';  
                }//end if
                if ($state['stateName'] == 'Florida') {

                    $analyze .= '<tr><th>'.$state['formName'].', here is info for: '.$state['stateName'].'</th></tr>';  


                    $analyze .= '<p>Much of Florida is situated on a peninsula between the Gulf of Mexico, the Atlantic Ocean, and the Straits of Florida. 
                        Its geography is marked by a coastline, by the omnipresence of water and the threat of hurricanes. Florida has the longest coastline in the contiguous United States, encompassing approximately 1,350 miles (2,170 km), and is the only state to border both the Gulf of Mexico and the Atlantic Ocean. 
                        Much of the state is at or near sea level and its terrain is characterized by sedimentary soils. 
                        The climate varies from subtropical in the north to tropical in the south.</p>';    
                }//end if
                if ($state['stateName'] == 'Colorado') {

                    $analyze .= '<tr><th>'.$state['formName'].', here is info for: '.$state['stateName'].'</th></tr>';  


                    $analyze .= '<p>Colorado is bordered by the northwest state of Wyoming to the north, the midwest states of Nebraska and Kansas to the northeast and east, on the south by New Mexico a small portion of the southern state of Oklahoma, on the west by Utah, and Arizona to the southwest. 
                        The four states of Colorado, New Mexico, Arizona, and Utah meet at one common point known as the Four Corners, which is known as the heart of the American Southwest. 
                        Colorado is one of only three U.S. states with no natural borders, the others being neighboring Wyoming and Utah. 
                        Colorado is noted for its vivid landscape of mountains, forests, high plains, mesas, canyons, plateaus, rivers, and desert lands.</p>'; 
                }//end if    
                if ($state['stateName'] == 'Texas') {

                    $analyze .= '<tr><th>'.$state['formName'].', here is info for: '.$state['stateName'].'</th></tr>';  


                    $analyze .= '<p>Due to its size and geologic features such as the Balcones Fault, Texas contains diverse landscapes that resemble both the American South and Southwest.
                        Although Texas is popularly associated with the Southwestern deserts, less than 10% of the land area is desert.
                        Most of the population centers are located in areas of former     prairies, grasslands, forests, and the coastline. 
                        Traveling from east to west, one can observe terrain that ranges from coastal swamps and piney woods, to rolling plains and rugged hills, and finally the           desert and mountains of the Big Bend.</p>'; 
                }//end if                       
                $analyze .= '</h1>';
                $analyze .= '<p><a href="testsad.php">Try again!</a></p>';

                return $analyze;
            }//end analyze()


            //page display

            if( empty ($_POST) )
            {
                echo display_form();


            }//end if
            else
            {
                echo display($_POST);
                echo display_form();
            }//end else

        ?>
4

3 回答 3

4
$alreadyRan = false;

function something() {
    global $alreadyRan;

    if( $alreadyRan ) return;
    $alreadyRan = true;

    // do something
}
于 2012-09-25T01:35:34.107 回答
4

使用静态的,而不是全局的。保持在功能范围内 - 更安全。http://php.net/manual/en/language.variables.scope.php

function RunOnce() { 
   static $ran = false; 

   if( $ran ) {
        // Already run;
   } else {
        $ran = true;
        // first run;  
   }
}
于 2012-09-25T01:38:49.897 回答
0

只需设置一个变量,该变量的值在函数运行时更改false为。true

所以它会是这样的:

$runbefore = false; // Initialize the variable
function foo() {
  global $runbefore;

  if ($runbefore == true) { // If it has been run,
    // Do stuff here if it has been run
  }
  // Do all your stuff here
  $runbefore = true; // tell the code it has been run, you must include this at the end
}

如果您在页面重新加载(1 小时)后仍需要支持,请执行以下操作:

function foo() {
  if (isset($_COOKIE['runbefore']) && $_COOKIE['runbefore'] === true) { // the function has been run before
    // Do stuff
  }
  // Do all your stuff here
  setcookie('runbefore', true, time() + 3600);
}
于 2012-09-25T02:06:22.827 回答