微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

重复属性的 PHP 8 错误:是否可以多次使用属性?

如何解决重复属性的 PHP 8 错误:是否可以多次使用属性?

我有一个属性如下:

#[Attribute]
class State{
    public function __constractor(
        public string $name
    ){}
}

我想将多个状态添加到我的类中,如下所示:

#[
   State('a'),State('b')
]
class StateMachine{}

一切正常,我可以访问属性列表如下:

$attrs = $classReflection->getAttributes(State::class);

但问题是,每当我尝试对其中一个进行即时处理时,都会抛出一个错误

$instance = $attrs[0]->newInstance();

错误是:

Error: Attribute "State" must not be repeated

有什么想法吗?

解决方法

根据官方文档,您必须以不同的方式定义您的属性才能做到这一点。我使用 PHPStorm 来验证我的假设,这应该可行:

定义属性

import discord
from discord.utils import get
from discord.ext import commands

#Créer une instance du bot
bot = commands.Bot(command_prefix='!')

#Donner le jeton pour l'identifier
jeton = "Here is the token"

#Detecter quand le bot est allumé
@bot.event
async def on_ready():
    print("Bot Prêt")
    await bot.change_presence(status=discord.Status.idle,activity=discord.Game('Hello World !'))
    print("Bonjour")

@bot.event
async def on_raw_reaction_add(payload):

    user_id = payload.user_id
    emoji = payload.emoji.name
    canal = payload.channel_id
    message = payload.message_id
    membre = bot.get_user(user_id)

    if canal == 826772563715555358 and message == 826773226675896340 and emoji == "python":
        print("Grade ajouté !")
        print(membre)


@bot.event
async def on_raw_reaction_remove(payload):

    emoji = payload.emoji.name
    canal = payload.channel_id
    message = payload.message_id

    if canal == 826772563715555358 and message == 826773226675896340 and emoji == "python":
        print("Grade enlevé !")



#Créer la commande !regles
@bot.command()
async def regles(ctx):
    await ctx.send("Les règles : \n1. Pas d'insulte \n2. Pas de double compte \n3. Pas de spam")

#Créer la commande !bienvenue
@bot.command()
async def bienvenue(ctx,member: discord.Member):
    pseudo = member.mention
    await ctx.send(f"Bienvenue {pseudo} ! ")

#tester l'erreur de la commande
@bienvenue.error
async def on_command_error(ctx,error):
    if isinstance(error,commands.MissingRequiredArgument):
        await ctx.send("Veuillez préciser une personne")


#Connecter le bot
bot.run(jeton)

此处的重要部分是 use Attribute; #[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS)] class State{ public function __construct( public string $name ){} } 定义。要使其适用于类,您还需要使用 Attribute::IS_REPEATABLE

根据docs,在应用属性时,您还应该将所有内容放在一行中:

Attribute::TARGET_CLASS

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。