属性与注解

元数据怎么挂、谁来读——PHP 8 Attributes 与 10 语言注解机制横评。

C C23

C23
#include <stdio.h>

/* C23 有真正的属性语法,但属性只是编译期提示:
   没有任何反射能在运行期把它们读回来 */
[[deprecated("use hello2 instead")]]
static const char *hello(void) { return "hi"; }

static const char *hello2(void) { return "hi v2"; }

int main(void) {
    /* 调用 hello() 只会触发编译器警告,不是运行期事件 */
    printf("%s\n", hello2());
    return 0;
}
输出
hi v2

C++ C++26

C++26
#include <cstdio>

// C++11 标准属性:编译期提示,没有运行期反射。
// [[nodiscard]] 让忽略返回值成为编译器警告。
[[nodiscard]] const char *hello() { return "hi"; }

int main() {
    std::printf("%s\n", hello());
    (void)hello(); // 显式转换压制 nodiscard 警告
    return 0;
}
输出
hi

C# v11.0.100

v11.0.100
using System;
using System.Reflection;

// 属性就是普通类;反射按需读回
var t = typeof(Controller);
var classRoute = t.GetCustomAttribute<RouteAttribute>();
Console.WriteLine($"class route: {classRoute?.Path}");
var m = t.GetMethod("Hello");
Console.WriteLine($"method route: {m?.GetCustomAttribute<RouteAttribute>()?.Path}");

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
class RouteAttribute : Attribute
{
    public string Path { get; }
    public RouteAttribute(string path) { Path = path; }
}

[Route("/api")]
class Controller
{
    [Route("/api/hello")]
    public string Hello() => "hi";
}
输出
class route: /api
method route: /api/hello

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"reflect"
)

// Go 没有属性机制;结构体标签是惯用的元数据通道,
// 用反射读回来
type Controller struct {
	Name string `route:"/api"`
}

func main() {
	t := reflect.TypeOf(Controller{})
	f, _ := t.FieldByName("Name")
	fmt.Println("tag:", f.Tag.Get("route"))
	fmt.Println("kind:", t.Kind())
}
输出
tag: /api
kind: struct

Java v27.0.1

v27.0.1
import java.lang.annotation.*;
import java.lang.reflect.Method;

// RUNTIME 保留策略让注解在运行期可反射读取
@Retention(RetentionPolicy.RUNTIME)
@interface Route {
    String value();
}

@Route("/api")
class Controller {
    @Route("/api/hello")
    public String hello() { return "hi"; }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Class<Controller> c = Controller.class;
        System.out.println("class route: " + c.getAnnotation(Route.class).value());
        Method m = c.getMethod("hello");
        System.out.println("method route: " + m.getAnnotation(Route.class).value());
    }
}
输出
class route: /api
method route: /api/hello

JavaScript v26.13.1

v26.13.1
// JS 没有属性语法;惯用法是元数据属性和以函数为键的旁表
function hello() { return "hi"; }
hello.route = "/api/hello";   // 元数据挂在函数对象上

const routes = new Map();     // 注册表模式:旁表
routes.set(hello, hello.route);
console.log("route:", routes.get(hello));
console.log("name:", hello.name);
输出
route: /api/hello
name: hello

PHP v8.6.0

v8.6.0
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class Route {
    public function __construct(public string $path) {}
}

#[Route('/api')]
class Controller {
    #[Route('/api/hello')]
    public function hello(): string { return "hi"; }
}

// 属性在被反射实例化之前完全惰性
$r = new ReflectionClass(Controller::class);
$route = $r->getAttributes(Route::class)[0]->newInstance();
echo "class route: ", $route->path, "\n";

$mRoute = $r->getMethod('hello')->getAttributes(Route::class)[0]->newInstance();
echo "method route: ", $mRoute->path, "\n";

$names = [];
foreach ($r->getAttributes() as $a) { $names[] = $a->getName(); }
echo "class attributes: ", implode(",", $names), "\n";
输出
class route: /api
method route: /api/hello
class attributes: Route

Python v3.15.2

v3.15.2
# 装饰器是 Python 最接近的惯用法:包装代码并可携带元数据
def route(path):
    def wrap(fn):
        fn.route = path      # 元数据挂在函数对象自身上
        return fn
    return wrap

@route("/api/hello")
def hello():
    return "hi"

print("route:", hello.route)
print("name:", hello.__name__)
输出
route: /api/hello
name: hello

Rust v1.99.1

v1.99.1
// 属性驱动编译器:derive 在编译期展开为 trait 实现;
// 没有任何运行期反射能把它们读回来
#[derive(Debug)]
struct Route {
    path: &'static str,
}

fn main() {
    let r = Route { path: "/api/hello" };
    println!("{:?}", r);
    println!("path: {}", r.path);
}
输出
Route { path: "/api/hello" }
path: /api/hello

TypeScript v26.13.1

v26.13.1
// TS 同样没有运行期元数据;类型只做描述,不做注解
function hello(): string { return "hi"; }
const routes = new Map<Function, string>();
routes.set(hello, "/api/hello");
console.log("route:", routes.get(hello), "name:", hello.name);
// stage-3 装饰器与旧 experimentalDecorators 都需要转译器支持
输出
route: /api/hello name: hello

语言差异说明

C:C23 标准属性 [[deprecated]]/[[nodiscard]] 等(示例):编译期提示,无运行期反射;框架式元数据只能靠宏 + 注册表手工搭。

C++:C++11 起标准属性(示例):[[nodiscard]] 让忽略返回值成编译警告;无运行期反射,静态反射(C++26)落地前元数据读取靠代码生成。

C#:Attribute 体系鼻祖级(示例):Attribute 类 + AttributeUsage 限定目标,Attribute.GetCustomAttribute 反射读取,newInstance 式即时可用——与 PHP Attributes 同构。

Go:无属性机制(示例):结构体标签 struct tag 是惯用元数据通道,reflect 读回 tag.Get;编码器(json/xml)全靠它驱动。

Java:注解(示例):@interface 声明,@Retention(RUNTIME) 才可运行期反射读取;编译期处理另有 APT 注解处理器一条路。

JavaScript:无属性语法(示例):惯用法是函数对象挂属性或旁表 Map 注册元数据;Stage 3 装饰器提案仍在路上,运行期反射读元数据无内建。

PHP:8.0+ Attributes(示例):#[...] 语法、属性类 #[Attribute] 声明目标,ReflectionAttribute::newInstance() 惰性实例化——读回靠反射,与注解驱动的框架(Symfony/Doctrine)深度绑定。

Python:装饰器(示例):包装并变换代码对象,元数据挂函数属性(fn.route)或 __annotations__;运行期可反射,但语义是「变换代码」而非「静态标注」。

Rust:#[derive(...)] 与属性宏(示例):编译期展开为代码(trait 实现/宏生成),零运行期反射——属性是编译器的输入而非数据。

TypeScript:语言层与 JS 相同(示例):类型只描述不注解;Stage 3 装饰器与旧 experimentalDecorators 均需转译器,Node 原生剥离模式下不可用。