doumi0737 2015-09-21 12:10
浏览 248
已采纳

Laravel MessageBag如何运作?

I encountered something magical about laravel (4.2), that i really want explaind how it could be possible.

When i up a MessageBag Class in Class A

And Pass that variable to Class B, somehow Class B overrides the Class A MessageBag without me declaring it.

class ClassA {

    public function test()
    {
        $msgBag = new \Illuminate\Support\MessageBag;

        new ClassB($msgBag);

        if($msgBag->any()) {
            #This will trigger and spit out "Message from Class B"
            dd($msgBag);
        }else{
            print('nope no messages');
        }
    }
}

class ClassB {

    protected $msgBag;

    function __construct(\Illuminate\Support\MessageBag $msgBag)
    {
        $this->msgBag = $msgBag;
        $this->setMessage();
    }

    public function setMessage()
    {
        $this->msgBag->add('message', 'Message from Class B');
    }
}

I tested the same thing with a normal object but that behaved like i expected it to.

class ClassA {

    public function test()
    {
        $object = (object) ['class'=>'A'];

        new ClassB($object);

        dd($object->class); # Will return A
    }
}

class ClassB {

    protected $object;

    function __construct($object)
    {
        $this->object = $object;
        $this->setMessage();
    }

    public function setMessage()
    {
        $this->object = (object) ['class'=>'B'];
    }
}

So obviously Laravel is doing something behind the seances to make this possible, but I haven't found it yet.

Does anyone know how to replicate this ?

  • 写回答

1条回答 默认 最新

  • dongyue9860 2015-09-21 12:25
    关注

    There is no Laravel magic here. In PHP, objects behave as though they are passed by reference (although they technically are not, but that's not relevant here).

    This means that in your first example, the MessageBag object you created is the same object as the as the one assigned to $this->msgBag in ClassB. Therefore, any modifications made to the object inside ClassB are going to be seen when you inspect the $msgBag object in the test() method in ClassA.

    This is not the case in your second example, because in your setMessage() method, you override the first object with an entirely new one.

    Basically everything is behaving as you would expect with normal PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看