How to set a private or protected property without a setter

By Ronald van Belzen | July 7, 2018

When you have a php class with private or protected properties without setters that you want to set for testing purposes, there are two possible ways to tackle that problem.

As an example I create the following class:

class Example {

  protected $var;

  public function __construct($var) {
    $this->var  = $var;
  }

}

The first approach uses reflection:

$ex = new Example('relection');

$reflectionClass = new \ReflectionClass('\Example');

$reflectionProperty = $reflectionClass->getProperty('var');
$reflectionProperty->setAccessible(true);

$reflectionProperty->setValue($ex, 'another value');

echo $reflectionProperty->getValue($ex);
// Outputs: another value

The second approach uses closure (PHP 5 >= 5.3.0, PHP 7) :

$ex = new Example('closure');
 
$changePropertyClosure = function () {
    $this->var = 'another value';
};
 
$setProperty = $changePropertyClosure->bindTo($ex, get_class($ex));
$setProperty();

$getPropertyClosure = function () {
    return $this->var;
};

$getProperty = $getPropertyClosure->bindTo($ex, get_class($ex));
echo $getProperty();
// Outputs: another value

 

Add new comment