【问题标题】:PHP 8 Attribute constructor callingPHP 8 属性构造函数调用
【发布时间】:2021-12-15 04:56:53
【问题描述】:

我正在尝试了解 PHP 中的属性是如何工作的。但是当我编写一些代码(我安装了支持 PHP 8 的 XAMPP)时,它似乎不起作用(屏幕上没有消息)。是否需要额外的配置才能工作?

use Attribute;

class MyAttribute {
    public function __construct($message) {
        // I want to show this message when using MyAttribute
        echo $message;
    }
}

#[MyAttribute('hello')]
class SomeClass {
    // ...
}

这段代码不应该显示“你好”消息吗?还是我不明白什么?它没有显示任何内容。

【问题讨论】:

  • 您是否希望它运行以# 开头的行
  • @NigelRen 如果您不知道,#[...] 是 PHP 8.0 中为属性 AKA 注释引入的语法。它在这里作为注释突出显示,并且将被早期版本的 PHP 视为一个(这是最终选择语法的原因之一),但它确实是对 MyAttribute 类构造函数的引用。这个问题是合理的,Kazz 的回答解释了缺失的部分。

标签: php php-8 php-attributes


【解决方案1】:

属性只能通过反射访问,示例如下:

// you have to specify that your custom class can serve as attribute
// by adding the build-in attribute Attribute:

#[Attribute] 
class MyAttribute {
    public function __construct($message) {
        // I want to show this message when using MyAttribute
        echo $message;
    }
}

#[MyAttribute('hello')]
class SomeClass {
    // ...
}

// first you need to create Reflection* in order to access attributes, in this case its class
$reflection = new ReflectionClass(SomeClass::class);
// then you can access the attributes
$attributes = $reflection->getAttributes();
// notice that its an array, as you can have multiple attributes
// now you can create the instance
$myAttributeInstance = $attributes[0]->newInstance();

一些文档:ReflectionClassReflectionAttribute

还有其他 Reflection* 类,例如:方法、函数、参数、属性、类常量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2016-08-29
    • 2022-12-16
    • 2014-08-21
    相关资源
    最近更新 更多