Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php annotations - minimal working example

Last time i checked (2008) annotations in php weren't so wide spread. Now after reading some material and having done some "googling", i am still a little confused. Could someone provide a minimal working example that illustrates how to use annotations in php:
Lets just say i want something like this to work:

class ClassName
{
  /**
  * @DefaultValue("test")
  */
  public $prop;
}

// so that i can do 

$kls = new ClassName();
$kls->prop // => test

I havent done php in a long while

UPDATE
The purpose of this question is to understand how libraries/frameworks like symfony,flow3 and doctrine implement their annotations.

like image 304
krichard Avatar asked Oct 23 '25 00:10

krichard


2 Answers

Annotations are not (yet) supported by PHP. There is an RFC for a proposed implementation, but it's still unknown if or when would that happen.

The particular example that you've given might be interpreted by an IDE as a value to auto-complete and otherwise you can just do public $prop = 'Test';, but I guess you already know that and it's not your real intention.

like image 185
Narf Avatar answered Oct 25 '25 14:10

Narf


In PHP Manual -> Function Reference Variable and Type Related Extensions -> Reflection, exists a method getDocComment() in several reflection classes (ReflectionClass, ReflectionMethod, ReflectionFunction, ReflectionFunctionAbstract, ReflectionProperty...) where you can get the doc comment block. Then process your comment the way you want. Example:

class Foo {
   private $a;
   private $b;
   ...
   /**
    * @annotation('baz')
    */
   public function bar() {
      ...
   }
}

$reflMethod = new ReflectionMethod('Foo', 'bar');

//prints 
//string(26) "/**
// * @annotation('baz')
// */"
var_dump($reflMethod->getDocComment());
like image 36
Mauro Avatar answered Oct 25 '25 13:10

Mauro