If you just want to check a file without loading it use token_get_all()
:
<?php
header('Content-Type: text/plain');
$php_file = file_get_contents('c2.php');
$tokens = token_get_all($php_file);
$class_token = false;
foreach ($tokens as $token) {
if (is_array($token)) {
if ($token[0] == T_CLASS) {
$class_token = true;
} else if ($class_token && $token[0] == T_STRING) {
echo "Found class: $token[1]\n";
$class_token = false;
}
}
}
?>
Basically, this is a simple finite state machine. In PHP the sequence of tokens will be:
T_CLASS
: 'class' keyword;
T_WHITESPACE
: space(s) after 'class';
T_STRING
: name of class.
So this code will handle any weird spacing or newlines you get just fine because it's using the same parser PHP uses to execute the file. If token_get_all()
can't parse it, neither can PHP.
By the way, you use token_name()
to turn a token number into it's constant name.
Here is my c2.php:
<?php
class MyClass {
public __construct() {
}
}
class MyOtherClass {
public __construct() {
}
}
?>
Output:
Found class: MyClass
Found class: MyOtherClass