How can I read Docblock from a PHP method to a string?

Asked

Viewed 133 times

0

I wonder how I can read the Docblock of a PHP method 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 method Stack::overflow and keep it in a variable?

  • http://www.phpdoc.org/ serves?

  • @Guilhermelautert, I think I expressed myself badly or you didn’t understand. I want to return the contents of the docblock method Stack::overlow in a string. That’s it?

1 answer

4


This can be done by using the getDocComment, that is present in the classes ReflectionMethod and ReflectionFunction.

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 method getMethod, an instance of ReflectionMethod is returned.

Observing

Remember that for Docblock to be captured, it is necessary that the comment contains two asterisks after the /.

Correct example:

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


 /*
 *
 */    

 public function invalido($value) {}

Browser other questions tagged

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