3v4l.org

run code in 300+ PHP versions simultaneously
<?php namespace Fake\BuiltIn\Functions; /** * Executes the given statements using fake built-in functions. * * @param callable $statements Statements to execute. * @return mixed Whatever $statements returns. * @throws \ReflectionException */ function fake(callable $statements) { $function = new \ReflectionFunction($statements); $start_line = $function->getStartLine(); $end_line = $function->getEndLine(); $function_source = implode('', array_slice(file($function->getFileName()), $start_line - 1, $end_line - $start_line + 1)); if (preg_match('/(?<={).*(?=})/s', $function_source, $matches)) { $function_body = $matches[0]; $namespace = __NAMESPACE__; return eval(" namespace $namespace; $function_body "); } throw new \RuntimeException('Failed to execute statements.'); } function strlen($string) { return 'fake result'; } namespace My\Name\Space; use function Fake\BuiltIn\Functions\fake; class MyClass { /** * @throws \ReflectionException */ public function testMethodWithFakeStrlen() { fake(function () { echo strlen('foo'), PHP_EOL; }); } public function testMethodWithoutFakeStrlen() { echo strlen('foo'), PHP_EOL; } } $myObject = new MyClass(); try { $myObject->testMethodWithFakeStrlen(); $myObject->testMethodWithoutFakeStrlen(); } catch (\ReflectionException $e) { // ... }
Output for 7.1.25 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
fake result 3
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 fake result 3

preferences:
200.36 ms | 402 KiB | 184 Q