I have a php file which contains only one class. how can I know what class is there by knowing the filename? I know I can do something with regexp matching but is there a standard php way? (the file is already included in the page that is trying to figure out the class name).
Share
There are multiple possible solutions to this problem, each with their advantages and disadvantages. Here they are, it’s up to know to decide which one you want.
Tokenizer
This method uses the tokenizer and reads parts of the file until it finds a class definition.
Advantages
Disadvantages
Code
Regular expressions
Use regular expressions to parse the beginning of the file, until a class definition is found.
Advantages
Disadvantages
echo "class Foo {";)Code
Note: The regex can probably be improved, but no regex alone can do this perfectly.
Get list of declared classes
This method uses
get_declared_classes()and look for the first class defined after an include.Advantages
Disadvantages
Code
Note: You cannot simply do
end()as others suggested. If the class includes another class, you will get a wrong result.This is the Tokenizer solution, modified to include a $namespace variable containing the class namespace, if applicable:
Say you have this class:
…or the alternative syntax:
You should have the following result:
You could also use the above to detect the namespace a file declares, regardless of it containing a class or not.