1

I'm using Random class to generate a password for a new user in my custom module.

I added the namespace in my module controller: use \Drupal\Component\Utility\Random;
And I am using it like this:

$user = User::create();
$user->setPassword(Random::string());

Problem is this function seems to be deprecated, however I found it in the Drupal API documentation.
Here is the error I get:

Deprecated function: Non-static method Drupal\Component\Utility\Random::string()

Did I use it wrong or do you know a better way to generate a random string ?

Drupal version: 8.4

1
  • 1
    user_password()
    – user21641
    Oct 19, 2017 at 10:39

1 Answer 1

7

Random::string isn't a static function, so you can't call it statically.

Well, you can (PHP is, erm, interesting like that), but it will throw a fatal error in future versions of the language, hence the warning now. To clarify, you're not being warned that Random::string itself is deprecated, just the method you're using to invoke it.

Get an instance instead and use that:

$random = new \Drupal\Component\Utility\Random();
$string = $random->string();
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.