亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過引用 Laravel 事件偵聽器傳遞數組

通過引用 Laravel 事件偵聽器傳遞數組

PHP
慕無忌1623718 2021-07-09 16:01:08
我在 Laravel 應用程序中有一個數組,我想在 Laravel 偵聽器中修改它。PHP 默認按值傳遞一個數組,但是,Laravel 事件及其偵聽器的工作方式我無法修改原始變量。有沒有比我在下面做的更好的方法?從中觸發事件的模型。型號:Event.phpnamespace Vendor\Package\Modelsuse Vendor\Package\Events\PageNodeArrayAfter;use Event;class Page{   public function toArray()   {      $data = [];       // do something with the data.       Event::fire(new PageNodeToArrayAfter($data))      // The data should be modified by a listener when I use it here.   }}事件:PageNodeToArrayAfter.phpnamespace Vendor\Package\Events;class PageNodeToArrayAfter{    /**     * Props to be sent to the view     * @var array $data     */    protected $data = [];    /**     * @param array $data     *      */    public function __construct(array &$data)    {        $this->data = $data;    }    public function getData()    {        return $this->data;    }}監聽器:FlashMessagesListner.phpnamespace Vendor\Package\Listeners;class FlashMessagesListner{    protected $data = [];    public function handle(PageNodeToArrayAfter $event)    {       $this->data = $event->getData();       // The problem here is the $data is no logner a reference here.     }}
查看完整描述

3 回答

?
富國滬深

TA貢獻1790條經驗 獲得超9個贊

根據數組的文檔,它是這樣說的:


數組賦值總是涉及值復制。使用引用運算符按引用復制數組。


因此,將您的構造函數更改為此:


// prepend the argument with the reference operator &

public function __construct(array &$data) 


查看完整回答
反對 回復 2021-07-16
  • 3 回答
  • 0 關注
  • 218 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號