While the words of Vilx are correct, one way around this is to use a static variable in the class:
Because your method is static
it is not really, truly inside any "class" but is more like a global. Therefore It can't "save" data between each time it runs, unless you use a "static" variable outside of the scope of the method, but within this class, alongside your "static" method.
Your life becomes much easier if you use a non-static class method reference (or if you use a superglobal such as a $_SESSION
variable). It all depends on what you're actually doing with this method.
However, the example code below defines a string and then repeat calls that string in the same PHP script, as exampled.
Class with Static Variable:
<?php
class twister {
public static $VALUEZ = ''; //this holds your generated code value.
public static function codeGenerator() {
if(empty(self::$VALUEZ)){
// Is unset so generate this value for the first time.
$length = 7;
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$output = null;
for ($i = 0; $i < $length; $i++) {
$output .= $characters[mt_rand(0, strlen($characters) - 1)];
}
self::$VALUEZ = $output;
}
else {
// value is not empty so simply throw it back out.
$output = self::$VALUEZ;
}
return $output;
} // close method.
} //close class
$claz = new twister();
print $claz::codeGenerator();
print "\n";
print $claz::codeGenerator();
print "\n";
print $claz::codeGenerator();
Output:
DVMbN0L
DVMbN0L
DVMbN0L