PHP's bindTo is evil

2025-10-19

Home

Did you know that in PHP you can access private variables in class A from class B?

Take a look at the following snippet:


<?php

class Innocent {
  private static $soul = 1886745189;

  public function getSoul(): int { // Set to mixed if you want to see the corruption
    return self::$soul;
  }
}

class Evil {
  public function corruptSoul(): void {
    $corrupSoulSpellScroll = static function () {
      Innocent::$soul = 'I hate encapsulation!!!!';
    };
    $corrupSoulSpell = $corrupSoulSpellScroll->bindTo(null, Innocent::class);
    $corrupSoulSpell();
  }
}

// Crazy that you can corrupt existing objects, though that's not so surprising if that class uses static
$civilian = new Innocent();
$warlock = new Evil();
echo $civilian->getSoul() . PHP_EOL;
$warlock->corruptSoul();
echo $civilian->getSoul() . PHP_EOL;

In general, I hate static. Whenever I see it, I groan, I know it's gonna cause issues.

Disclaimer: I'm not a PHP expert, I've coded in it for about a year in a legacy stack. There's probably some explanation for why this is the case (I think visiblity came after bindTo, so it's probably related to that).

Relevant links: