保留PHP函数中的变量值

时间:2014-01-07 18:55:51

标签: php

我有一个函数,我在脚本中多次调用。函数返回的值将始终相同。我不想每次都执行函数内的所有脚本,因为返回的值总是相同的。我没有使用OOP,因此无法将其分配给对象属性并在构造函数中执行脚本。

以下是我的尝试。它不起作用,因为$ status在以后定义为静态变量之前未设置。我怎样才能实现目标?

function checkStatus()
{
    if(!isset($status))
    {
        //Do some script to determine $cond
        if($cond) {static $status=0;}
        else {static $status=1;}
    }
    return $status;
}

2 个答案:

答案 0 :(得分:1)

这应该做你需要的:

function checkStatus()
{

  static $status;

  if(!isset($status))
  {

    if (TRUE) // Whatever your truth condition will be
    {
      $status = 1;
    }

    else
    {
      $status = 0;
    }

  }

  return $status;

}

答案 1 :(得分:0)

您可以通过引用传递变量:http://www.php.net/manual/en/language.references.pass.php

function checkStatus(&$status)
{
    //Do some script to determine $cond
    if($status == 0) { 
      $status=1;
    }
    else {
      $status=0;
    }
  }

$status = 0;
checkStatus($status);
echo $status; //this should display 1;