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 ?