PHP "permanent variable"

3.5k views Asked by At

I'm currently working at a WordPress Plugin. It supports shortcode and creates DOM elements, when the shortcode is called.

Now my problem: I want to identify the elements.

So when the shortcode gets called the first time it should return something like

<div class="myClass-0"></div>

and when it gets called the second time

<div class="myClass-1"></div>

And so on.

Any ideas on this issue? Thanks for help

Julian.

3

There are 3 answers

16
Ry- On BEST ANSWER

You could use a static variable. A static variable holds its value globally and is preserved between function calls:

function doSomething() {
    static $i = 0;
    ##############

    return $i++;
}

doSomething(); // 0
doSomething(); // 1

Here's a demo. It will work in class methods too, of course, though depending on the situation you might be better off using an instance variable.

1
sathishkumar On

If you need between the different request, There is no permanent variable in php You should use session or database for this requirement.

0
Julian F. Weinert On

Nothing of your Ideas worked for me.

WordPress seems to delete all static and non-staitc variables. And session variables too.

Now I got a new idea and fixed the issue by using random numbers. I wrote this function:

function jw_rand($length)
{
    $return = "";
    for($a = 0; $a < $length; $a++)
    {
        $return .= mt_rand(0,9);
    }
    return $return;
}

Then I call it via <?php echo("<div class=\"myClass-".jw_rand(5)."\"></div>"); ?>

This doesn't count my classes... But at least I can identify the divs. And I don't think that the chance is high for two identical results of this function.

Thanks for help though. Maybe some WordPress pro can answer my question, explaining how the plugin- and shortcode integration works and why variables disappear after calling the plugin once.

Greets Julian