在laravel中召集一个事件

时间:2018-01-05 13:41:23

标签: php laravel

我以这种方式召集活动:

event(new NewsLetterActivation($user));

并且事件:

public $user;
public function __construct(User $user)
{
    $this->user = $user;
}

有效。

现在有时,我有一个额外的字符串变量,也可能没有 $ user($ user为空或null)。

我怎么称呼它?

我试试这个:

event(new NewsLetterActivation(null,'a@a.com'));

并且在事件中:

public function __construct(User $user,$email=null)
{
        $this->user = $user;
        $this->email= $email;
}

错误:

Type error: Argument 1 passed to App\Events\NewsLetterActivation::__construct() must be an instance of App\Events\User, null given

3 个答案:

答案 0 :(得分:3)

Since PHP 7.1您可以执行此操作以传递null

public function __construct(?User $user)

答案 1 :(得分:1)

将您的控制器更改为以下内容 -

public function __construct($user,$email=null)
{
    $this->user = $user;
    $this->email= $email;
}

答案 2 :(得分:1)

__construct()方法或监听器中,您必须更改输入参数:

public function __construct(array $arg)
{
    if (isset($agr['user])) {
        $this->user = $agr['user];
    }
    if (isset($arg['email'])) {
        $this->email= $agr['email'];
    }
}

然后你可以通过不同的方式调用事件:

event(new NewsLetterActivation(['email'=>'a@a.com']);
event(new NewsLetterActivation(['email'=>'a@a.com', 'user'=>$user]);
event(new NewsLetterActivation(['user'=>$user]);
event(new NewsLetterActivation([]);