[PHP] Modifying a private class property at runtime

Published on 2019-12-03 • Modified on 2019-12-03

In this snippet, we will see how to read and modify a private property of a PHP object. I recently had a concrete case when I have created my EasyDeploy configuration. I had to modify a private property of the DefaultConfiguration object to make it work for my environment.

<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet61Trait.php

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;

 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet61Trait
    public function snippet61(Request $request): void
        $class = \get_class($request);
        echo sprintf('> Request value object class: %s'.PHP_EOL, $class);

        // This line would provoke a PHP error as the "isHostValid" is private
        // echo $request->isHostValid;

        $property = (new \ReflectionClass($request))->getProperty('isHostValid');
        $property->setAccessible(true); // now we can read and write "isHostValid"
        echo '> isHostValid: '.$property->getValue($request).PHP_EOL;

        $property->setValue($request, false);
        echo '> isHostValid: '.$property->getValue($request);

        // That's it! 😁

 Run this snippet  More on Stackoverflow   Read the doc