How to read comments of a class, function or method?

Asked

Viewed 115 times

4

I’ve seen some implementations in the Symfony and Laravel framework that allow you to define through comments routes in controller methods, or the Doctrine Models' Annotation definitions.

Sort of like this:

class Usuariosontroller

{
    /**
     * @Route('GET', 'usuarios')
    */
    public function getIndex()
    {

    }

}

How frameworks do to read this block of comments on top of the methods?

2 answers

7


Class

Using the ReflectionClass to access the class, and thus get the value of the comment using the method getDocComment:

$reflection = new ReflectionClass('Usuariosontroller');
echo $reflection->getDocComment();

Example Ideone.

Method

Also using the ReflectionClass to access the class, now use the getMethod to access the method you want to obtain the information using the method getDocComment:

$reflection = new ReflectionClass('Usuariosontroller'); 
echo $reflection->getMethod('getIndex')->getDocComment();

Example Ideone.

Function

Use the ReflectionFunction to access the function, in sequence the getDocComment to access the comment:

$reflection = new ReflectionFunction('beber');
$reflection->getDocComment()    

Example Ideone.

Observing:

There are a few ways to comment, but the above methods only work if you use the comment whose token is T_DOC_COMMENT, that is, comments that obey syntax: /** */, then comments using token T_COMMENT - syntax // or #, and /* */ - will be ignored.

  • 1

    Ball show, it was beautiful. Accept

1

You can also use token_get_all php native.

filing cabinet index php.

/**

    COMENTÁRIO

*/

function foo(){
    echo "foo";
}

Running...

$array = token_get_all(file_get_contents("index.php"));

foreach($array as $arr){
    if(isset($arr[0]) && ($arr[0] == T_DOC_COMMENT || $arr[0] == T_COMMENT)){
        print_r($arr[1]);
    }
}

exit:

/** COMMENTING */

Browser other questions tagged

You are not signed in. Login or sign up in order to post.