Skip to content

Instantly share code, notes, and snippets.

View perrelet's full-sized avatar

perrelet

View GitHub Profile
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
@perrelet
perrelet / PHP `extract_class_name` from file
Last active January 24, 2025 16:46
PHP - Extract Class Name from File
<?php
function extract_class_name ($file) {
// https://stackoverflow.com/questions/7153000/get-class-name-from-file
// fix: $class = $tokens[$i+2][1]; ---> if (is_array($tokens[$i+2])) $class = $tokens[$i+2][1]; Avoids 'Uninitialized string offset 1' when using 'static::class'
// fix: if ($tokens[$j][0] === T_STRING) { ---> if ($tokens[$j][0] === T_STRING || $tokens[$j][0] === T_NAME_QUALIFIED) { Handle files with sub-namespaces (T_NAME_QUALIFIED PHP 8.0.0+)
// fix: add: if ($tokens[$j] === ';') break; Class declarations can't contain a semi-colon. Bailing early speeds things up and prevents confusing lines containing '::class' with the class declaration.
function php_token_lookup ($token) {
$tokens = [
T_ABSTRACT => 'T_ABSTRACT ==> abstract - Class Abstraction',
T_AND_EQUAL => 'T_AND_EQUAL ==> &= - assignment operators',
T_ARRAY => 'T_ARRAY ==> array() - array(), array syntax',
T_ARRAY_CAST => 'T_ARRAY_CAST ==> (array) - type-casting',
T_AS => 'T_AS ==> as - foreach',
T_BOOLEAN_AND => 'T_BOOLEAN_AND ==> && - logical operators',
T_BOOLEAN_OR => 'T_BOOLEAN_OR ==> || - logical operators',