php - Sharing a property between objects -


this might sound bit confusing, why i'm here i'm doing wrong. following logic of example code below, i'm trying create "shared property" class extending b can modify property of a, , class c have access it.

class {     public $shared = null; }  class b {     public $a;     public $c;      function __construct()     {         $this->a = new a();         $this->c = new c($this->a->shared);     } }  class c {     public $test;      function __construct(&$shared)     {         $this->test = &$shared;          var_dump($this->test);     } }  class test extends b {     $this->a->shared = 'success'; } 

the logic seems work pessimism kicking in. passing reference correctly, or there better way achieve i'm after without passing reference?

you shouldn't need pass reference @ all, objects inherently passed reference in php >= 5.0; long same instance of a being used, same value of shared used.

which say, pass around reference 'a', , not particular member variable.

of course, can play references directly, doing in code. notwithstanding syntactic incorrectness of test class @ time, concept correct. if change test class follows (and run):

class test extends b {     public function __construct() {         parent::__construct();          $this->a->shared = 'success';     } }  var_dump(new test); 

i following output:

null // <-- first var_dump in c::__construct()  object(test)[1]   public 'a' =>      object(a)[2]       public 'shared' => &string 'success' (length=7)   public 'c' =>      object(c)[3]       public 'test' => &string 'success' (length=7) 

am simpler example:

class { public $f; } class b { public $f; }  $a = new a; $b = new b;  $a->f = 1; $b->f = &$a->f;  $a->f = 2;  var_dump($a, $b); 

produces

object(a)[1]   public 'f' => &int 2 object(b)[2]   public 'f' => &int 2 

and can many times need to. in better way, poor sample.


Comments

Popular posts from this blog

blackberry 10 - how to add multiple markers on the google map just by url? -

php - guestbook returning database data to flash -

delphi - Dynamic file type icon -