1

PHP で、保護/プライベート プロパティへの参照をプロパティのスコープ外のクラスに返すと、その参照はスコープをオーバーライドしますか?

例えば

class foo
{
  protected bar = array();
  getBar()
  {
    return &bar;
  }

}

class foo2
{
  blip = new foo().getBar(); // i know this isn't php
}

これは正しく、配列 bar は参照によって渡されていますか?

4

1 に答える 1

4

サンプルコードは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

于 2008-09-16T05:50:24.813 に答える