每次调用时更改变量值

I've used a variable that is set by choosing a word from an array (using time as the "random" index) throughout a site. Everything works great.

However - on some pages that variable is displayed multiple times, and each time it displays the same word.

Because I've hardcoded the variable (and randomly generated it on page load), it will be a massive headache to go through and change the variable to a function that instead returns the word. (This was not done in the first place for a reason - that didn't take the duplication into account.)

Here's the question: Is there a way to make a variable change its value each time its called?

I was thinking something along the lines of

<?php
$var = function returnNewWord(){
      /* generate random word here */
      return $ranWord;
}
?>

That does not work - but it may give you an idea of what I mean.

Anyone know how this may be possible? Thank you for your help.

The only way this is really possible, is if you turn it into an instance of a class:

<?php

class RandomThingy {

   function __toString() {

      $ranWord = mt_rand(1, 1000);
      /* generate random word here */
      return (string)$ranWord;

   }

}

$var = new RandomThingy();

print $var;
print $var;

?>

If there is a finite array of words, there is a high chance that you will receive same outputs for multiple functions calls.

If you want to get fully random variable:

 <?php
    function returnNewWord() {
        $length = 10;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
    $var = returnNewWord();
    echo $var;
    ?>

That should do it.

<?php
$array = array("foo", "bar", "hello", "world");
$var = function returnNewWord(){
      $ranIndex = rand(0, count($array));
      $ranWord = $array[$ranIndex];
      array_splice($array, $ranIndex, 1);
      return $ranWord;
}
?>