PHP开发 之 注解

目录

  • 开始

  • 注解

    • 类注解

    • 属性注解

开始

mkdir annotation && cd annotation

mkdir -p module/Base

vim module/Base/Description.php
vim composer.json
{
    "autoload": {
        "psr-4": {
            "Base\\": "module/Base/"
        }
    }
}
composer update

关于命名空间 更多参考PHP学习 之 namespace

vim index.php

关于自动加载 更多参考PHP学习 之 autoload

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

关于PHP环境搭建 更多参考PHP开发 之 开发环境

注解

composer require doctrine/annotations

vim module/Base/Description.php

关于doctrine/annotations 更多参考Doctrine Annotations

类注解

vim index.php
getClassAnnotations($reflectionClass);
        foreach ($classAnnotations as &$classAnnotation)
        {
            var_dump($classAnnotation);
        }
    }
}

$annotationDemo = new AnnotationDemo();

关于PHP反射 更多参考PHP: 反射

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

属性注解

vim module/Base/Di.php
vim index.php
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);

关于ReflectionProperty 更多参考PHP: ReflectionProperty

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

参考

  • Doctrine Annotations

  • PHP的Annotations之doctrine/annotations

你可能感兴趣的:(PHP开发 之 注解)