How can I read the Docblock of a PHP method for a string?

0

I would like to know how I can read the Docblock of a method in PHP and turn it into a string.

For example, I have the following code:

class Stack
{
     /**
      * @return void
     */
     public function overflow()
    {
    }

}

How could I get the docblock of the Stack::overflow method and save it in a variable?

    
asked by anonymous 02.09.2015 / 17:49

1 answer

4

You can do this by using the getDocComment method, which is present in the ReflectionMethod and ReflectionFunction classes.

See the description of the method in Documentation .

/**
* This is an Example class
*/
class Example
{
    /**
     * This is an example function
     */
    public function fn() 
    {
        // void
    }
}

$reflector = new ReflectionClass('Example');

// to get the Class DocBlock
echo $reflector->getDocComment()

// to get the Method DocBlock
$reflector->getMethod('fn')->getDocComment();

In the example above we use ReflectionClass . But when we call the getMethod method, an instance of ReflectionMethod is returned.

Note

Note that for Docblock to be captured, the comment must contain two asterisks after / .

Correct example:

 /**
 * @param string $value
 **/
 public function correto($value) {}


 /*
 *
 */    

 public function invalido($value) {}
    
02.09.2015 / 18:29