开发者

Generating a random number in CakePHP?

In my cakephp controller, I want to have a variable that stores a random number that any funct开发者_开发知识库ion can access. The random number variable will indicate a certain array that multiple functions will use. I've tried a bunch of variations of the rand() function, most recently:

$rand = rand(1, 4);

outside of the controller class and inside the controller class. Can anyone help? Much appreciated?

Andrew


Add something like this to your controller:

function beforeFilter() {
  $this->myRandomNumber = rand(1,4);
}

Now you can use $this->myRandomNumber from everywhere within the controller. It will stay the same during the request.


Is this number changing constantly? If not, why not set a random variable in your config file.

If yes, use rand and store it....or if you want letters too, use something like md5(time + salt)


Does the random generator function has to do anything with databases? If no, I would add the function to bootstrap.php at config folder


I would rather use array_rand if the random number would change depending on the size of an array.

You can put the variable in a config file if the random number should be constant within the same request, or make a model/plugin to store a method that does this precise line:

return array_rand($my_array);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜