Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if class exists within file without requiring/including

Tags:

php

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?

like image 755
tomsseisums Avatar asked Oct 17 '11 09:10

tomsseisums


3 Answers

$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

like image 175
deceze Avatar answered Nov 10 '22 04:11

deceze


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.

like image 22
Eineki Avatar answered Nov 10 '22 04:11

Eineki


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.

like image 1
daiscog Avatar answered Nov 10 '22 05:11

daiscog