问题描述
#[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