Thatdude22
Thatdude22

Reputation: 57

How do i get this function to run once in PHP?

I'm trying to get the random function to run once so that every user would have 1 unique string.

I don't understand why it's not working. I used static variable but still it runs more than once.

Any suggestions ?

Thank you.

//
function RandomStr($length = 10)
{
    static $state = false;
    if ($state) return;

    $state = true;

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
echo RandomStr();
//

Upvotes: 1

Views: 107

Answers (2)

Sherif
Sherif

Reputation: 11942

The state of a static variable only exists in the scope of a single request. What you're suggesting is that you want to retain the state per user, not per request. To do that you will need to maintain state outside of PHP, like in your database or perhaps a session (if you want to retain the state per session).

e.g.

function RandomStr($length = 10)
{
    session_start();
    $state = $_SESSION['state'] ?? false;
    if ($state) return;

    $_SESSION['state'] = true;

    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Of course, be mindful that doing session_start() inside of a function is probably not realistic. So just consider this is only meant as a contrived example.

Upvotes: 6

Progrock
Progrock

Reputation: 7485

Reducing your function - this seems to work as I'd expect:

<?php

function return_true_once()
{
    static $state = false;
    if ($state) return;

    $state = true;

    return true;
}
var_dump(return_true_once());
var_dump(return_true_once());

Output:

bool(true)
NULL

Upvotes: 1

Related Questions