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();

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
    – user21641
    Commented Oct 19, 2017 at 10:39

1 Answer 1


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();

Your Answer

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

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