tags:

views:

148

answers:

4

Hello, 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.

+1  A: 

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'] . "'\n";

This outputs:

foo[c] = ''
Bill Karwin
thanks, but that was a simple typo and fixing it does not affect the behaviour described
Ok, I went on and did more tests. Still cannot observe any problem.
Bill Karwin
+3  A: 

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"
Owen
+5  A: 

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.

yjerem
just a note, php5 does return objects by reference, but anything else by value as you note.
Owen
A: 

Okay, you're right. I tried to make a simple example of my problem, but indeed the above works, and so does my code. Working with a debugger, I got "Referenco to..." as value and "Soft Reference" as type. Hence I thought of an error. Apparently this is only an issue of the debugger's tracking - thanks anyway!