サンプルコードはPHPではありませんが、保護された変数への参照を返す場合は、その参照を使用して、クラスのスコープ外のデータを変更できます。次に例を示します。
<?php
class foo {
protected $bar;
public function __construct()
{
$this->bar = array();
}
public function &getBar()
{
return $this->bar;
}
}
class foo2 {
var $barReference;
var $fooInstance;
public function __construct()
{
$this->fooInstance = new foo();
$this->barReference = &$this->fooInstance->getBar();
}
}
$testObj = new foo2();
$testObj->barReference[] = 'apple';
$testObj->barReference[] = 'peanut';
?>
<h1>Reference</h1>
<pre><?php print_r($testObj->barReference) ?></pre>
<h1>Object</h1>
<pre><?php print_r($testObj->fooInstance) ?></pre>
このコードを実行すると、に格納されているデータがに格納されている参照を使用して変更print_r()
されたことが結果に示されます。ただし、キャッチは、関数が参照によって返されるものとして定義されている必要があり、呼び出しも参照を要求する必要があるということです。あなたはそれらの両方が必要です!これに関するPHPマニュアルの関連ページは次のとおりです。$testObj->fooInstance
$testObj->barReference
http://www.php.net/manual/en/language.references.return.php