1

Given an array like this:

array(
     /** I'm foo! */
     'foo' => 1,

     /** I'm bar! */
     'bar' => 2,
);

Is it possible to retrieve the DocComments for the array elements? As far as I know, the Reflection API doesn't provide a mechanism for this. If it is possible, I'm guessing it will have to be a pretty "creative" solution.

TaylorOtwell
  • 7,177
  • 7
  • 32
  • 42
  • 1
    these are not doccomments but just comments. also, your example doesnt specify the context of where this is encountered, e.g. class, function or mere file. – Gordon Apr 11 '11 at 14:13
  • Why would you want to do this? Comments are for humans, using them in this manner seems counter-intuitive. – Adam Pointer Apr 11 '11 at 14:16
  • @Adam Pointer: Not really. Comments can be used for a lot of things (see PHPDocumentor and PHPUnit). Also, in Java, they are actually useful for the compiler (e.g.: the @exception tag). – netcoder Apr 11 '11 at 14:23
  • @netcoder - True, it all depends on the context, phpdocumentor parses docblocks, but comments in PHP are not used by the interpreter. Which leads us back to my original question, why would you want to this? – Adam Pointer Apr 11 '11 at 14:28

1 Answers1

1

The Reflection API will not be able to do this by itself (or not at all if it's not a class). Per example, with this code:

<?php

$bar = array(
     /** I'm foo! */
     'foo' => 1,

     /** I'm bar! */
     'bar' => 2,
);

The Reflection API is useless here (no classes, no functions). You can still get it using the tokenizer:

$code = file_get_contents('input.php');

$tokens = token_get_all($code);
foreach ($tokens as $key => $token) {
    if (is_array($token)) {
        if ($token[0] == T_DOC_COMMENT) {
            for ($i=$key+1; $i<count($tokens); $i++) {
                if (is_array($tokens[$i]) && $tokens[$i][0] != T_WHITESPACE) {
                     echo $tokens[$i][2] . ' = '.$token[1].PHP_EOL;
                     break;
                }
            }
        } /* T_DOC_COMMENT */
    }
}

This will print:

'foo' = /** I'm foo! */
'bar' = /** I'm bar! */

However, keep in mind that this is done on a very small example. If you want to go about parsing a complete PHP file (with classes, functions, etc.), you'll be in for a bumpy ride.

In conclusion, it's possible, but it involves a lot of work and is very error-prone. I wouldn't recommend it. There might be an actual PHP parser that exists, but I never used one so I can't tell.

Community
  • 1
  • 1
netcoder
  • 66,435
  • 19
  • 125
  • 142