在 null 上调用成员函数 encodePassword(),Symfony 4

Call to a member function encodePassword() on null, Symfony 4

我正在尝试使用 UserPasswordEncoderInterface class 将编码密码保存到我的实体中。

class UserFixture extends Fixture
{
private $encoder;

public function _construct( UserPasswordEncoderInterface $encoder){
    $this->encoder = $encoder;
}

public function load(ObjectManager $manager)
{
    $user = new User();
    $user->setUsername('admin');
    $user->setPassword(
        $this->encoder->encodePassword($user, '0000')
    );
    $user->setEmail('no-reply@hotmail.com');
    $manager->persist($user);

    $manager->flush();
    }
}

但我收到以下错误:Call to a member function encodePassword() on null。在这里找不到我做错了什么!

您应该首先检查您的命名空间,但正如@Cerad 所说,您输入错误的 __construct() 这就是您的 encoder 为空的原因。

正确加载夹具的命令可能是:

php bin/console doctrine:fixtures:load

按照文档的建议:https://symfony.com/doc/master/bundles/DoctrineFixturesBundle/index.html