3v4l.org

run code in 200+ PHP versions simultaneously
<?php class Foo { protected string $property; public function __construct(string $property) { $this->property = $property; } public function getProperty(): string { return $this->property; } } $foo = new Foo("foo"); echo "Default value:\n"; var_dump($foo->getProperty()); // ------------------------- Method 1 ------------------------- echo "\nInvoking the __constructor() method again:\n"; $foo->__construct("bar"); var_dump($foo->getProperty()); // ------------------------- Method 2 ------------------------- // https://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/ echo "\nClosure binding:\n"; Closure::bind( function (): void { $this->property = "baz"; }, $foo, $foo )->__invoke(); var_dump($foo->getProperty()); // ------------------------- Method 3 ------------------------- echo "\nAbusing anonymous classes:\n"; $fooAbuser = new class("") extends Foo { public function abuse(Foo $foo): void { $foo->property = "boom"; } }; $fooAbuser->abuse($foo); var_dump($foo->getProperty());
based on Ta4PM
Output for 7.4.0 - 7.4.6
Default value: string(3) "foo" Invoking the __constructor() method again: string(3) "bar" Closure binding: string(3) "baz" Abusing anonymous classes: string(4) "boom"
Output for 7.2.0 - 7.3.18
Parse error: syntax error, unexpected 'string' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in /in/fNTRa on line 4
Process exited with code 255.