作为相同字符串传递的随机字符串 php

Random String passed as the same string php

尝试使用 PHP 和 Behat 创建一个功能测试,我想要一个电子邮件的随机字符串,但我希望每次新测试 运行 时字符串都是随机的,但是我想将创建的相同字符串作为参数传递给不同的测试。

因此,如果我生成一个 10 位数字的字符串,我想生成该字符串,然后将其作为相同的 10 位数字序列通过其他测试

我是 PHP 的新手,所以我不太清楚如何设置它,但这是我目前在 Behat 上下文文件中的内容

class FeatureContext implements Context {

private $MailPage;
private $registrationpage;


/**
 * Initializes context.
 *
 * Every scenario gets its own context instance.
 * You can also pass arbitrary arguments to the
 * context constructor through behat.yml.
 */
public function __construct(MailPage $mailPage, RegistrationPage $registrationpage)
{
    // Page obects injected directly in constructor with type hints.
    $this->MailPage = $MailPage;
    $this->registrationpage = $registrationpage;
}

/**
 * @BeforeSuite
 */
public static function  generateRandomString() {

    // Generate random string for Email implementation.
    $randomString = bin2hex(openssl_random_pseudo_bytes(10));
    return $randomString;

}


/**
 * @Given /^I register a temporary email address $/
 */
public function iRegisterATemporaryEmailAddress()
{
    $this->MailPage->grabNewEmail(self::generateRandomEmail());
}

/**
 * @Given /^I register a Developer account$/
 */
public function iRegisterADeveloperAccount()
{

    $this->registrationpage->fillInFormDetails(self::generateRandomEmail());
}

我 运行 遇到的问题是,按原样使用参数,每次调用它都会生成不同的字符串,但我只希望它为整个套件生成一次。有什么想法吗?

1- 从构造函数中调用您的方法。

2- 使用 this

将生成的值保存在变量中
private $randomString ;
public function __construct(MailPage $mailPage, RegistrationPage $registrationpage)
{
   //your code
   $this->randomString = $this->generateRandomString();

}

3- 要使用此变量,您可以在 class 方法中调用它,例如 $this->randomString.

Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.