PHP静态变量,需要帮助在函数中计数吗

PHP静态变量,需要帮助在函数中计数吗,php,Php,我有一个函数,它接受输入变量并通过以下调用输出模板: outputhtml($blue_widget); outputhtml($red_widget); outputhtml($green_widget); 以及该函数的简化版本: function outputhtml($type) { static $current; if (isset($current)) { $current++; } else { $

我有一个函数,它接受输入变量并通过以下调用输出模板:

outputhtml($blue_widget);
outputhtml($red_widget);
outputhtml($green_widget);
以及该函数的简化版本:

function outputhtml($type)
{

    static $current;
    if (isset($current))
    {
        $current++;
    }
    else
    {
        $current = 0;
    }

//some logic here to determine template to output

return $widget_template;

}
现在我的问题来了。如果我在脚本中调用函数三次或更多次,我希望输出是单向的,但是如果我只调用函数两次,那么我需要在返回的模板中反映一些html更改

那么我如何修改这个函数来确定是否只有两个调用呢。我不能事后再问你你只跑了两次吗


我很难理解我是如何告诉一个函数在第二次之后它将不会被使用,并且可以使用必要的html修改的。如何实现这一点?

在函数中使用静态$current是不实际的;我建议使用对象来维护状态,如下所示:

function outputhtml($type)
{
    static $current = 0;
    $current++;

    //some logic here to determine template to output
    if ($current === 2) {
       // called twice
    }

    if ($current > 2) {
       // called more than twice
    }
    return $widget_template;

}
class Something
{
    private $current = 0;

    function outputhtml($type)
    {
        // ... whatever
        ++$this->current;
        return $template;
    }

    function didRunTwice()
    {
        return $this->current == 2;
    }
}
didruntweep方法是询问您是否运行了两次

$s = new Something;
$tpl = $s->outputhtml(1);
// some other code here
$tpl2 = $s->outputhtml(2);
// some other code here
if ($s->didRunTwice()) {
    // do stuff with $tpl and $tpl2
}

如果一个函数只被调用了两次,唯一可以确定的方法是将测试放在代码末尾;但到那时,这些模板可能已经无法访问了?如果看不到更多的代码,就说不出什么。

在函数中使用静态$current是不实际的;我建议使用对象来维护状态,如下所示:

class Something
{
    private $current = 0;

    function outputhtml($type)
    {
        // ... whatever
        ++$this->current;
        return $template;
    }

    function didRunTwice()
    {
        return $this->current == 2;
    }
}
didruntweep方法是询问您是否运行了两次

$s = new Something;
$tpl = $s->outputhtml(1);
// some other code here
$tpl2 = $s->outputhtml(2);
// some other code here
if ($s->didRunTwice()) {
    // do stuff with $tpl and $tpl2
}

如果一个函数只被调用了两次,唯一可以确定的方法是将测试放在代码末尾;但到那时,这些模板可能已经无法访问了?如果没有看到更多的代码,就说不出什么。

如果$current==2{//调用两次}或者如果$current>2,那么使用它不是更好吗{?效率更高。但这是我的问题。如果计数为1或2,我需要输出某个css类。我想我仍然不知道如何正确地执行此操作。我知道如果current==2,但我们如何知道函数不会再次调用?因为如果超过两次,则输出的css类是不同的。模板中引用了$current变量以提供一些不同的标记内容。如果$current===2{//called tweep}elseif$current>2,那么使用$current不是更好吗{?效率更高。但这是我的问题。如果计数为1或2,我需要输出某个css类。我想我仍然不知道如何正确地执行此操作。我知道如果current==2,但我们如何知道函数不会再次调用?因为如果超过两次,则输出的css类是不同的。模板中引用了$current变量,以便为标记提供一些不同的内容。