2012-01-11 34 views

回答

3

創建私有財產$methodHasBeenRun,其默認值爲FALSE,並在該方法中將其設置爲TRUE。在方法的開始,做:

if ($this->methodHasBeenRun) return; 
$this->methodHasBeenRun = TRUE; 
+0

謝謝你的迴應! – ATLChris 2012-01-11 23:13:22

-1

我會推薦這個版本

class example { 
    function __construct($run_magic = false) { 
     if($run_magic == true) { 
      //Run your method which you want to call at initializing 
     } 
     //Your normale code   
    } 
} 

,所以如果你不想運行它創建類像

new example(); 

,如果你想要

new example(true); 
1

您沒有指定恰恰爲什麼你只想在某些方法被調用時只運行一次給定的方法,但我會猜測你正在加載或初始化某些東西(可能是來自數據庫的數據),而且你不需要浪費每次循環。

@DaveRandom提供了一個很好的答案,肯定會有效。這裏是另一種方式,你可以做到這一點:

class foo { 
    protected function loadOnce() { 
      // This will be initialied only once to NULL 
      static $cache = NULL; 

      // If the data === NULL, load it 
      if($cache === NULL) { 
        echo "loading data...\n"; 
        $cache = array(
          'key1' => 'key1 data', 
          'key2' => 'key2 data', 
          'key3' => 'key3 data' 
        ); 
      } 

      // Return the data 
      return $cache; 
    } 

    // Use the data given a key 
    public function bar($key) { 
      $data = $this->loadOnce(); 
      echo $data[$key] . "\n"; 
    } 
} 

$obj = new foo(); 

// Notice "loading data" only prints one time 
$obj->bar('key1'); 
$obj->bar('key2'); 
$obj->bar('key3'); 

這部作品的原因是,你聲明緩存變量static。有幾種不同的方法可以做到這一點。你可以使該類的成員變量,等等。