php - Referencing the same variable across two different classes -


<?php  class foo{     public $basket;      public function __construct()     {         $this->basket = 1;     }      public function getbasket(){         return $this->basket;     } }  class bar{     public function __construct(&$basket)     {         $basket++;     } }  $newfoo = new foo(); $newbar = new bar($newfoo->getbasket());  echo $newfoo->getbasket();  ?> 

i hoping initialise $basket value in 1 class , manipulate same variable via class. unfortunately, keep getting "notice: variables should passed reference in " error message.

question: how can change code make happen? thank you.

change

$newbar = new bar($newfoo->getbasket()); 

to

$basket = $newfoo->getbasket(); $newbar = new bar($basket); 

the first way doesn't work because php doesn't have variable hold value you're passing new bar() consequence, nothing can passed reference.

the second way works because $basket var fixed reference in memory, can passed reference new bar()

you asked in comments:

have changed code yours. echo $newfoo->getbasket(); produces 1 (i hoping 2).

1 produced because each call getbasket() gives fresh copy of class variable. $basket passed new bar() equals 2, that's not you're echoing.

if want result of getbasket() , variable $basket refer same reference in memory, need make 2 changes:

1 change function declaration to:

public function &getbasket() 

2 change how store function result to:

$basket = &$newfoo->getbasket(); 

now echo return 2 because have unique basket reference throughout code

see docs


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -