Beto Aveiga
Beto Aveiga

Reputation: 3670

Why this code is not changing

In the code below I would expect that real_change and change methods to change the variable $n passed by reference in the constructor.

abstract class y {
  private $x;

  function __construct(&$x) {
    $this->x = &$x;
  }

  function real_change() {
    $this->x = 'real change';
  }
}

class x extends y {    
  function change() {
    $this->x = 'changed';
  }
}

$n = 'intact';
$c = new x($n);
$c->change(); 
echo $n.PHP_EOL; // prints "intact"
$c->real_change();
echo $n.PHP_EOL; // prints "real change"

Why is this happening?

How could I achieve to create a method in an abstract class that modifies a variable referenced in a property?

Many thanks.

Upvotes: 0

Views: 42

Answers (1)

Blue
Blue

Reputation: 22911

In your abstract class, $x is marked as private, so it's not available to your extended class. $this->x will essentially just create a new public $x variable in class x.

If you set the variable to protected it will give access to all extended classes, and allow you to set it properly.

See updated playground here.

More information on visibility via the PHP docs, can be found here.

Upvotes: 2

Related Questions