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 ?

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.