I have a class which has a private member $content
. This is wrapped by a get-method:
class ContentHolder
{
private $content;
public function __construct()
{
$this->content = "";
}
public function getContent()
{
return $this->content;
}
}
$c = new ContentHolder();
$foo = array();
$foo['c'] = $c->getContent();
Now $foo['c']
is a reference to content
, which is what I don't understand. How can I get the value? Thank You in advance.
In PHP, you don't say: "$foo = new array();
" Instead, you simply say: "$foo = array();
"
I ran your code (PHP 5.2.6) and it seems to work fine. I tested it by dumping the array:
var_dump($foo);
This outputs:
array(1) {
["c"]=>
string(0) ""
}
I can also simple use echo
:
echo "foo[c] = '" . $foo['c'] . "'
";
This outputs:
foo[c] = ''
i'm not quite understanding your question. say you changed:
public function __construct() {
$this->content = "test";
}
$c = new ContentHolder();
$foo = array();
$foo['c'] = $c->getContent();
print $foo['c']; // prints "test"
print $c->getContent(); // prints "test"
I just tried your code and $foo['c']
is not a reference to $content
. (Assigning a new value to $foo['c']
does not affect $content
.)
By default all PHP functions/methods pass arguments by value and return by value. To return by reference you would need to use this syntax for the method definition:
public function &getContent()
{
return $this->content;
}
And this syntax when calling the method:
$foo['c'] = &$c->getContent();
See http://ca.php.net/manual/en/language.references.return.php.