Is there a way to check if class exists within a file without including/requiring the class?
Something like: class_in_file($file);
As I already mentioned, I know this can be done with requiring/including the class and then looking up class_exists($class);
, but any other ways?
$tokens = token_get_all(file_get_contents('foo.php'));
Then go through the tokens to see if you can spot a certain T_CLASS
entry.
http://www.php.net/manual/en/function.token-get-all.php
http://www.php.net/manual/en/tokens.php
A php file is a text file, you can open it and parse it in order to find a class declaration.
It isn't a simple process, but a good parser should make the task trivial.
You have to strike out commented lines, strings containing a class declaration can trigger a false-positive, heredocs tend to make things more complex. Evals should be taken in account also.
if you have access to a command line php interpreter, then you can have a look at -w switch that strips comments and whitespaces for you doing a good half of yor work for you.
The short answer is no. There are only workarounds. For example, you could parse the file yourself (perhaps using token_get_all
), or perhaps mark the file somehow with a comment at the top like
<?php
/** #has_class(CLASSNAME)
*/
and read the first few lines looking for this with a preg_match
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With