PHP 注解

mkdir annotation && cd annotation

mkdir -p module/Base

vim module/Base/Description.php
<?php

namespace Base;

class Description
{
    public $desc = 'default';
}
vim composer.json
{
    "autoload": {
        "psr-4": {
            "Base\\": "module/Base/"
        }
    }
}
composer update
vim index.php
<?php

require "vendor/autoload.php";

use Base\Description;

var_dump(new Description());

测试

php index.php
object(Base\Description)#3 (1) {
  ["desc"]=>
  string(7) "default"
}

注解

composer require doctrine/annotations

vim module/Base/Description.php
<?php

namespace Base;

/**
 * @Annotation
 */
class Description
{
    public $desc = 'default';
}

类注解

vim index.php
<?php

use Doctrine\Common\Annotations\AnnotationRegistry;
use Doctrine\Common\Annotations\AnnotationReader;

$loader = require __DIR__ . '/vendor/autoload.php';
AnnotationRegistry::registerLoader(array($loader, 'loadClass'));

use Base\Description;

/**
 * @Description(desc="class")
 */
class AnnotationDemo
{

    public function __construct()
    {
        $annotationReader = new AnnotationReader();
        $reflectionClass = new ReflectionClass(get_class($this));

        /**
         * class annotations
         */
        $classAnnotations = $annotationReader->getClassAnnotations($reflectionClass);
        foreach ($classAnnotations as &$classAnnotation)
        {
            var_dump($classAnnotation);
        }
    }
}

$annotationDemo = new AnnotationDemo();

测试

php index.php
object(Base\Description)#13 (1) {
  ["desc"]=>
  string(5) "class"
}

属性注解

vim module/Base/Di.php
<?php

namespace Base;

/**
 * @Annotation
 */
class Di
{
    public $class = null;
}
vim index.php
<?php

# 省略了未修改代码

use Base\Description;
use Base\Di;

/**
 * @Description(desc="class")
 */
class AnnotationDemo
{
    /**
     * @Di(class="Base\Description")
     */
    private $desc;

    public function __construct()
    {
        # 省略了未修改代码

        /**
         * property annotations
         */
        foreach ($reflectionClass->getProperties() as &$property)
        {
            $propertyAnnotations = $annotationReader->getPropertyAnnotations($property);
            foreach ($propertyAnnotations as &$propertyAnnotation)
            {
                /**
                 * @var Di $propertyAnnotation
                 */
                $reflectionClass = new ReflectionClass($propertyAnnotation->class);
                $property->setAccessible(true);
                $property->setValue($this, $reflectionClass->newInstance());
            }
        }
    }
}

$annotationDemo = new AnnotationDemo();
var_dump($annotationDemo);

测试

php index.php
object(AnnotationDemo)#3 (1) {
  ["desc":"AnnotationDemo":private]=>
  object(Base\Description)#9 (1) {
    ["desc"]=>
    string(7) "default"
  }
}

https://www.jianshu.com/p/e7d4b05ba715?hmsr=toutiao.io