1

I want to read comments defined in a specific format next to properties of a PHP Class. e.g.

Class Test
{
   public $name; //(:Username)
   public $Dob; //(:BirthDate)
}

I want a similar output like some array which gives me $name and Username.

I have tried with using PHP Reflection Class but it doesn't work like how I want it to be:

$reflection = new ReflectionClass('Test');
print_r($reflection->getProperty("name")->getDocComment());
yivi
  • 42,438
  • 18
  • 116
  • 138
Muhammad Arslan Jamshaid
  • 1,077
  • 8
  • 27
  • 48
  • It doesn't allow me to use my comment format. It has it's own – Muhammad Arslan Jamshaid Nov 04 '18 at 08:56
  • 3
    `getDocComment` will only return PHPDoc formatted comments, I believe anything else is removed by the compiler. You could use Reflection to find the file the property is defined in, but you'd then have to parse it manually, either with a regex or ideally by tokenizing it. [This post](https://stackoverflow.com/questions/18257158/how-to-extract-start-line-of-a-property-declaration-in-php) might be a good start. – iainn Nov 04 '18 at 08:57

1 Answers1

2

If you want your custom annotations to be available for Reflection::getDocComment, you need to format your annotation using PHPDoc format.

E.g.

/** :Username */
public $whatever;

The double asterisk is what differentiates a T_COMMENT token from a T_DOC_COMMENT token.

The first type of token is stripped during code compilation by the engine, but the second one is appropriately tokenized and cached, so it's available at runtime (and thus, for use with Reflection).

yivi
  • 42,438
  • 18
  • 116
  • 138