Как получить доступ к защищенной переменной php

Как получить доступ к защищенной переменной php

Короткая история как получить доступ к переменной php, если ее зона видимости ограничена без ReflectionMethod* магии.

public - Class members declared public can be accessed everywhere.
protected - Class members declared protected can be accessed only within the class itself and by inheriting and parent classes.
private - Class members declared as private may only be accessed by the class that defines the member.

Важно, объекты одного типа будут иметь доступ к свойствам друг друга вне зависимости от их зоны видимости даже если они инициализированы в разных местах

Создадим класс с private свойством и получим доступ к нему:

<?php

class Test
{
  private $secret;
  public function __construct(string $secret)
  {
    $this->secret = $secret;
  }
  public function access(Test $other)
  {
    var_dump('access to private');
    var_dump($other->secret);
  }
}

$r = new Test('init class');
$r->access(new Test('Luke, I am your father.'));
//expected output
//access
//Luke, I am your father.

Как мы можем это использовать, например, поменять значение с переменной без сеттера и даже можем инициализировать класс с приватным конструктором

<?php

class Test {

  private string $name;

  private function __construct() {}

  public function getName(): string {
    return $this->name;
  }

  public static function setFromConfig(array $row): self {

    $Test = new Test;
    $Test->name = $row['name'];

    return $Test;
  }

}

$Test = Test::setFromConfig(['name'=>'Harry Potter']);
echo $Test->getName();


PS

*Как получить доступ к private переменной используя reflection

<?php

class Foo
{
  private $privateProperty = 'Harry Potter!';
}

$method = new ReflectionProperty('Foo', 'privateProperty');
$method->setAccessible(true);

echo $method->getValue(new Foo);
// Expected output
// Harry Potter!