Skip to content
Advertisement

Does PHP class property scope overridden by passing as reference?

In PHP, if you return a reference to a protected/private property to a class outside the scope of the property does the reference override the scope?

e.g.

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

}

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

Is this correct and is the array bar being passed by reference?

Advertisement

Answer

Well, your sample code is not PHP, but yes, if you return a reference to a protected variable, you can use that reference to modify the data outside of the class’s scope. Here’s an example:

<?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>

When this code is executed, the print_r() results will show that the data stored in $testObj->fooInstance has been modified using the reference stored in $testObj->barReference. However, the catch is that the function must be defined as returning by reference, AND the call must also request a reference. You need them both! Here’s the relevant page out of the PHP manual on that:

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement