title: How to know if a function is called first time or not
body: <p>I want to create a function such that if it is called the first time, it behaves differently and for rest of the time it behaves differently. Now to do this I know I can use a "state" variable. Some other techniques were also given here:
  <a href="https://stackoverflow.com/questions/1933050/check-if-function-has-been-called-yet">Check if function has been called yet</a></p>
  
  <p>However I somehow got a hint from a colleague that debug_backtrace() can be used to solve this problem. I read about it but cannot understand how ? This function gives a stack trace of the function call. How can this tell if the function has been called first time or not ?</p>
  
  <p>The exact code that baffles me is here:</p>
  
  <pre><code>/**
   * Holds the states of first timers
   * @var array
   */
  private static $firstTimeCSS=array();
  private static $firstTimeJS=array();
  /**
   * Tells whether it is the first time this function is called on 
   * ANY CLASS object or not. Useful for one-time scripts and styles
   * 
   * @param string $class name optional. Usually you should send __CLASS__ to this, otherwise the instance ($this) class would be used.
   * @return boolean
   */
  final protected function IsFirstTime($class=null)
  {
      $t=debug_backtrace();
      if ($t[1]['function']=="JS")
          $arr=&amp;self::$firstTimeJS;
      else
          $arr=&amp;self::$firstTimeCSS;
  
  
      if ($class===null)
          $class=$this-&gt;Class;
      if (isset($arr[$class]))
          return false;
      else
      {
          $arr[$class]=true;
          return true;
      }   
  }
  </code></pre>