absentx
absentx

Reputation: 1417

PHP static variable, need help counting in a function

I have a function that takes an input variable and outputs a template with the following call:

outputhtml($blue_widget);
outputhtml($red_widget);
outputhtml($green_widget);

And a simplified version of the function:

function outputhtml($type)
{

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

//some logic here to determine template to output

return $widget_template;

}

Now here is my problem. If I call the function in a script three times or more, I want the output to be one way, but if I only call the function twice, then I have some html changes that need to be reflected in the templates that are returned.

So how can I modify this function to determine if there are only two calls for it. I can't go back after the fact and ask "hey function did you only run twice???"

Having trouble getting my head around how I tell a function that it is not going to be used after the second time and the necessary html modifications can be used. How would I go about accomplishing this?

Upvotes: 1

Views: 94

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173572

That would not be practical using a static $current inside the function; I would suggest using an object to maintain the state instead, like so:

class Something
{
    private $current = 0;

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

    function didRunTwice()
    {
        return $this->current == 2;
    }
}

The didRunTwice() method is asking "did you run twice?".

$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
}

The only way you can find out if a function was only called twice is by putting the test at the end of your code; but perhaps by then the templates are no longer accessible? Can't tell much without seeing more code.

Upvotes: 1

xdazz
xdazz

Reputation: 160853

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;

}

Upvotes: 5

Related Questions