3v4l.org

run code in 300+ PHP versions simultaneously
<?php // Some other tool which polyfills the token constants, but doesn't care about the values at all. // If the values are not unique, the code in the Tokens::polyfillTokenizerConstants() method can not currently it. if (!defined('T_PROTECTED_SET')) { define('T_PROTECTED_SET', 10000); } if (!defined('T_ENUM')) { define('T_ENUM', 10000); } Tokens::polyfillTokenizerConstants(); var_dump(Tokens::tokenName(T_PROTECTED_SET)); var_dump(Tokens::tokenName(T_ENUM)); class Tokens { /** * Mapping table for polyfilled constants * * @var array<int, string> */ private static $polyfillMappingTable = []; public static function tokenName($token) { if (is_string($token) === true) { // PHPCS native token. return substr($token, 6); } return (self::$polyfillMappingTable[$token] ?? token_name($token)); } /** * Polyfill tokenizer (T_*) constants. * * {@internal IMPORTANT: all PHP native polyfilled tokens MUST be added to the * `PHP_CodeSniffer\Tests\Core\Util\Tokens\TokenNameTest::dataPolyfilledPHPNativeTokens()` test method!} * * @return void */ public static function polyfillTokenizerConstants(): void { // Ideally this would be a private class constant. We cannot do that // here as the constants that we are polyfilling in this method are // used in some of the class constants for this class. If we reference // any class constants or properties before this method has fully run, // PHP will intitialise the class, leading to warnings about undefined // T_* constants. $tokensToPolyfill = [ 'T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG', 'T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG', 'T_ATTRIBUTE', 'T_BAD_CHARACTER', 'T_COALESCE_EQUAL', 'T_ENUM', 'T_FN', 'T_MATCH', 'T_NAME_FULLY_QUALIFIED', 'T_NAME_QUALIFIED', 'T_NAME_RELATIVE', 'T_NULLSAFE_OBJECT_OPERATOR', 'T_PRIVATE_SET', 'T_PROTECTED_SET', 'T_PUBLIC_SET', 'T_READONLY', ]; // <https://www.php.net/manual/en/tokens.php> // The PHP manual suggests "using big numbers like 10000" for // polyfilled T_* constants. We have arbitrarily chosen to start our // numbering scheme from 135_000. $nextTokenNumber = 135000; $polyfillMappingTable = []; foreach ($tokensToPolyfill as $tokenName) { if (defined($tokenName) === false) { while (isset($polyfillMappingTable[$nextTokenNumber]) === true) { $nextTokenNumber++; } define($tokenName, $nextTokenNumber); } $polyfillMappingTable[constant($tokenName)] = $tokenName; } // Be careful to not reference this class anywhere in this method until // *after* all constants have been polyfilled. self::$polyfillMappingTable = $polyfillMappingTable; } }

preferences:
21.42 ms | 409 KiB | 5 Q