Encapsulation in PHP - member returns weird link

I have a class that has a private member $content

. This is wrapped by the 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 link to content

which I don't understand. How can I get a quote? Thank you in advance.

+1


source to share


3 answers


I just tried my code and $foo['c']

no reference to $content

. (Assigning a new value has $foo['c']

no effect $content

.)

By default, all PHP functions / methods pass arguments by value and return by value. To follow a link, you will need to use this syntax to define a method:

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 .

+5


source


I don't quite understand your question. let's 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"

      

+3


source


In PHP, you don't say " $foo = new array();

" Instead, you just say " $foo = array();

"

I ran your code (PHP 5.2.6) and it seems to work fine. I tested it by dropping the array:

var_dump($foo);

      

Output:

array(1) {
  ["c"]=>
  string(0) ""
}

      

I can also just use echo

:

echo "foo[c] = '" . $foo['c'] . "'\n";

      

Output:

foo[c] = ''

      

+1


source







All Articles