<?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 am hoping to initialise the $basket
value in one class and manipulate the same variable via another class. Unfortunately, I keep getting the "Notice: Only variables should be passed by reference in " error message.
Question: How can I change the code to make this 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 any variable with which to hold the value you're passing to new Bar()
As a consequence, nothing can be passed by reference.
The second way works because the $basket
var is a fixed reference in memory, so it can be passed by reference to new Bar()
You asked in comments:
have changed my code to yours. echo $newFoo->getBasket(); produces 1 (I was hoping for 2).
1
is produced because each call to getBasket()
gives you a fresh copy of the class variable. The $basket
that I passed to new Bar()
equals 2, but that's not what you're echoing.
If you want the result of getBasket()
and the variable $basket
to refer to the same reference in memory, you need to make two changes:
1 Change the function declaration to:
public function &getBasket()
2 Change how you store the function result to:
$basket = &$newFoo->getBasket();
Now your echo will return 2
because you would have a unique basket reference throughout your code