PHP属性的范围通过传递为参考被覆盖了吗?

时间:2020-03-05 18:55:10  来源:igfitidea点击:

在PHP中,如果将对受保护/私有属性的引用返回给属性范围之外的类,该引用会覆盖范围吗?

例如

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

}

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

这是正确的吗,数组栏是否通过引用传递?

解决方案

回答

好吧,示例代码不是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()结果将显示存储在$ testObj-> fooInstance中的数据已使用存储在$ testObj-> barReference中的引用进行了修改。但是,要注意的是,必须将函数定义为按引用返回,并且调用还必须请求引用。我们都需要它们!这是有关PHP手册的相关页面:

http://www.php.net/manual/zh/language.references.return.php