3v4l.org

run code in 300+ PHP versions simultaneously
<?php /* In each Child::foo() scenario, Parent::foo() cannot be intercepted (mocked) */ class Parent { public function foo() { echo 'Parent' . PHP_EOL; } } // Calling parent:: class Child_1 extends Parent { public function foo() { echo 'Child_1' . PHP_EOL; // Follow the method chin upward - Parent::foo() parent::foo(); } } class Mock_Child_1 extends Child_1 { public function foo() { echo 'Mock 1' . PHP_EOL; // Follow the method chain upward - Child_1::foo() parent::foo(); } } $mock1 = new Mock_Child_1(); $mock->foo(); /* Result: * Mock 1 * Child 1 * Parent - but we weren't able to intercept this to change its output! */ // Calling $this class Child_2 extends Parent { public function foo() { echo 'Child_2' . PHP_EOL; // Call the lowest foo() in the instance $this->foo(); } } class Mock_Child_2 extends Child_1 { public function foo() { echo 'Mock 2' . PHP_EOL; // Call the lowest foo() in the instance $this->foo(); } } $mock2 = new Mock_Child_2(); $mock->foo(); /* Result: * Mock 2 * Mock 2 ... (infinite) * * Mock_Child must call parent::foo() to get any higher in the chain */ // Mix class Child_3 extends Parent { public function foo() { echo 'Child_3' . PHP_EOL; // Call the lowest foo() in the instance $this->foo(); } } class Mock_Child_3 extends Child_1 { public function foo() { echo 'Mock 3' . PHP_EOL; // Follow the method chain upward - Child_2::foo() parent::foo(); } } $mock3 = new Mock_Child_3(); $mock->foo(); /* Result: * Mock 3 * Child 3 * Mock 3 * Child 3 ... (infinite) */
Output for 8.0.1 - 8.0.30, 8.1.0 - 8.1.26, 8.2.0 - 8.2.13, 8.3.0
Fatal error: Cannot use 'Parent' as class name as it is reserved in /in/MusWD on line 5
Process exited with code 255.

preferences:
189.53 ms | 1395 KiB | 78 Q