tags:

views:

493

answers:

3

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?

+3  A: 

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

Nathan Strong
Thanks, it was the notation i was confused about (*both* needing referencing tags)
Karan
A: 

Forgive me, but use a public variable and lose the need to "hack" access to a protected variable? What you are doing seems like a fairly bad idea... Perhaps if you told us more of what you were trying to accomplish, we could find a good way to go about it...

Scott S.
This is a very specialized instance where i need to access this property (for normalizing the db in relation to the flatfile content). For the other 99/100 times this property is accessed, it is better off being private.
Karan
Isn't that why we have these things called getters?For example:class Foo {private int bar;int getBar() { return this.bar; }}
Scott S.
Yes, but it wouldn't be a referenced value if i used a getter, it would just be a copy. But i need(ed) to edit the original variable, hence the question :P
Karan
A: 

I think the same would happen in C/C++ or any language having pointers.

phjr