๐ŸŽ“ A1Learner
๐Ÿ”
0 of 27 lessons completed

Attributes

An attribute is a piece of data attached to a class, a property or a method. The data sits in the code and waits until some other code reads it.

An attribute placed on a class

The Label class is marked as an attribute class. A Label with the text Book sits on the Book class, and the program prints a plain line because placing the attribute runs nothing.

<?php
#[Attribute]
class Label {
  public function __construct(public string $text) {
  }
}
#[Label("Book")]
class Book {
}
echo "Book ready\n";

An attribute with an argument on a property

The Hint attribute carries one text argument. It sits on the name property of the Form class, and the property value itself prints as usual.

<?php
#[Attribute]
class Hint {
  public function __construct(public string $text) {
  }
}
class Form {
  #[Hint("Shown above the field")]
  public string $name = "Ana";
}
$f = new Form();
echo $f->name . "\n";

Flags allow a repeated attribute on a method

The Tag definition joins two flags with a pipe sign. The repeatable flag lets two Tag attributes sit on one method, and the method still runs as a plain method.

<?php
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class Tag {
  public function __construct(public string $text) {
  }
}
class Jobs {
  #[Tag("fast")]
  #[Tag("safe")]
  public function run() {
    return "done";
  }
}
$j = new Jobs();
echo $j->run() . "\n";

Example

<?php
#[Attribute]
class Label {
  public function __construct(public string $text) {
  }
}
class SignupForm {
  #[Label("Full name")]
  public string $name = "Ana";
  #[Label("Email address")]
  public string $email = "ana@example.com";
}
$f = new SignupForm();
echo $f->name . " / " . $f->email . "\n";

Key points

  • An attribute is written in square brackets after a hash sign.
  • An attribute class is a plain class marked with the built-in Attribute attribute.
  • Placing an attribute runs nothing at that moment.
  • An attribute can take arguments, like a short constructor call.
  • Flags on the Attribute marker say where an attribute may sit and whether it may repeat.

In this example, the SignupForm class carries one Label on each of its two properties. Each label stores the words a form would show beside that field. The printed line shows the stored values, and the labels wait for a reader.

Note

Attributes only store data, so a program needs a separate step that reads the data back.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens at the moment an attribute is placed on a class?