Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

如何在Magento 2中生成随机字符串或数字?

在Magento 2中,您可以使用核心Magento \ Framework \ Math \ Random类生成随机数或随机字符串。

使用Random.php类,您可以使用Magento最佳编码实践生成随机字符串和随机数,而无需依赖PHP核心功能。

我创建了一个Block PHP文件,为演示添加了function()

class Demo extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Math\Random $mathRandom,
        array $data = []
    ) {
        $this->mathRandom = $mathRandom;
        parent::__construct($context,$data);
    }
 
    // Return a random number in the specified range
    public function getRandomNumber($min = 0, $max = null)
    {
        return $this->mathRandom->getRandomNumber($min, $max);
    }
 
    // Generate Random string
    public function getRandomString($length,  $chars = null)
    {
        return $this->mathRandom->getRandomString($length, $chars);
    }
}

为了生成随机的Magento本地字符串,使用一个字符
const CHARS_LOWERS ='abcdefghijklmnopqrstuvwxyz';
const CHARS_UPPERS ='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const CHARS_DIGITS ='0123456789';

要获取随机数字,您需要在函数中传递范围值,

echo $this-> getRandomNumber(1,7); //产生1到7之间的随机数字
echo $this-> getRandomString(5); //从(A-Za-z0-9)生成5个字符长的字符串

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论