php - How does Laravel MessageBag work? -


i encountered magical laravel (4.2), want explaind how possible.

when messagebag class in class a

and pass variable class b, somehow class b overrides class messagebag without me declaring it.

class classa {      public function test()     {         $msgbag = new \illuminate\support\messagebag;          new classb($msgbag);          if($msgbag->any()) {             #this trigger , spit out "message 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 class b');     } } 

i tested same thing normal object behaved expected to.

class classa {      public function test()     {         $object = (object) ['class'=>'a'];          new classb($object);          dd($object->class); # return     } }  class classb {      protected $object;      function __construct($object)     {         $this->object = $object;         $this->setmessage();     }      public function setmessage()     {         $this->object = (object) ['class'=>'b'];     } } 

so laravel doing behind seances make possible, haven't found yet.

does know how replicate ?

there no laravel magic here. in php, objects behave though passed reference (although technically not, that's not relevant here).

this means in first example, messagebag object created same object as 1 assigned $this->msgbag in classb. therefore, modifications made object inside classb going seen when inspect $msgbag object in test() method in classa.

this not case in second example, because in setmessage() method, override first object entirely new one.

basically behaving expect normal php.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -