i have a function
function createRandomString($length) {
$string = md5(time());
$highest_startpoint = 32-$length;
# use hexdec to get a "number only" format
$randomString = hexdec(substr($string,rand(0,$highest_startpoint),$length));
return $randomString;
}
$randomID = createRandomString(7);
and i want to be able to use the random string created in other functions
for example:
function new() {
echo '<input name="id" type="text" value="'.$randomID.'" disabled="disabled">';
}
However the random ID does not show up in the new function (aka its blank).
I need to define the random ID as a variable once so that the number remains constant throughout the script since if I defined it in every function you would get a different number using this method.
Is there a way of defining the variable randomID using the script at the top and keeping it constant throughout all functions calling it?
Well, though I’d advise against it, the easiest fix for what you’re trying to do in the
newfunction is:But there are a few more, and better ways to achieve the same result:
using classes:
using arguments, as Zulkhaery Basrul’s answer shows. You can make the argument optional by giving a default value of
nullin your function defenition.However, since that answer is now deleted:
Declaring constants:
Classes have constants, too. You can define them in an abstract class, so all child classes have access to the same randomId. As an added bonus (and potential pitfall) class constants, defined at the parent level can be overruled by the child class. So be careful!