初めて呼び出された場合は異なる動作をし、残りの時間は異なる動作をするような関数を作成したいと考えています。これを行うために、「状態」変数を使用できることがわかりました。他のいくつかのテクニックもここで与えられました: 関数がまだ呼び出されているかどうかを確認してください
しかし、同僚から debug_backtrace() を使用してこの問題を解決できるというヒントを得ました。私はそれについて読みましたが、どのように理解できませんか? この関数は、関数呼び出しのスタック トレースを提供します。関数が初めて呼び出されたかどうかをどのように判断できますか?
私を困惑させる正確なコードは次のとおりです。
/**
* 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=&self::$firstTimeJS;
else
$arr=&self::$firstTimeCSS;
if ($class===null)
$class=$this->Class;
if (isset($arr[$class]))
return false;
else
{
$arr[$class]=true;
return true;
}
}