Supported docblock annotations#

Psalm supports a wide range of docblock annotations.

PHPDoc tags#

Psalm uses the following PHPDoc tags to understand your code:

  • @var Used for specifying the types of properties and variables
  • @return Used for specifying the return types of functions, methods and closures. On a constructor, it gives the type of the object new creates (see Constructors)
  • @param Used for specifying types of parameters passed to functions, methods and closures
  • @property Used to specify what properties can be accessed on an object that uses __get and __set
  • @property-read Used to specify what properties can be read on object that uses __get
  • @property-write Used to specify what properties can be written on object that uses __set
  • @method Used to specify which magic methods are available on object that uses __call.
  • @deprecated Used to mark functions, methods, classes and interfaces as being deprecated
  • @internal Used to mark classes, functions and properties that are internal to an application or library.
  • @mixin Used to tell Psalm that the current class proxies the methods and properties of the referenced class.

Off-label usage of the @var tag#

The @var tag is supposed to only be used for properties. Psalm, taking a lead from PHPStorm and other static analysis tools, allows its use inline in the form @var Type [VariableReference].

If VariableReference is provided, it should be of the form $variable or $variable->property. If used above an assignment, Psalm checks whether the VariableReference matches the variable being assigned. If they differ, Psalm will assign the Type to VariableReference and use it in the expression below.

If no VariableReference is given, the annotation tells Psalm that the right-hand side of the expression, whether an assignment or a return, is of type Type.

<?php
/** @var string */
$a = $_GET['foo'];

/** @var string $b */
$b = $_GET['bar'];

function bat(): string {
    /** @var string */
    return $_GET['bat'];
}

@mixins#

Adding @mixin to a classes docblock tells Psalm that the class proxies will proxy the methods and properties of the referenced class.

class A
{
    public string $a = 'A';

    public function doA(): void
    {
    }
}

/**
 * @mixin A
 */
class B
{
    public string $b = 'B';

    public function doB(): void
    {
    }

    public function __call($name, $arguments)
    {
        (new A())->$name(...$arguments);
    }

    public function __get($name)
    {
        (new A())->$name;
    }
}

$b = new B();
$b->doB();
$b->doA(); // works
echo $b->b;
echo $b->a; // works

The members of the class, of its parent classes and of its interfaces, their @methods and @propertys included, come first. A member the class lacks is looked up in its mixins in declaration order, then in those of its traits, then in those of its parent class, and so on. The mixins of a mixin are looked up right after it, and the first mixin with the member wins:

class Deep { public function a(): int { return 1; } }
class Near { public function a(): string { return ''; } public function d(): string { return ''; } }
class Other { public function b(): bool { return true; } }
class Far { public function b(): float { return 1.0; } public function c(): float { return 1.0; } }

/** @mixin Deep */
class Middle {}

/** @mixin Other */
trait Forwards {}

/** @mixin Far */
abstract class Base { public function __call(string $name, array $args): mixed { return null; } }

/**
 * @method null d()
 * @mixin Middle
 * @mixin Near
 */
class Child extends Base { use Forwards; }

$child = new Child();
$child->a(); // int: Deep, the mixin of Middle, comes before Near
$child->b(); // bool: the mixin of a trait comes before that of the parent class
$child->c(); // float
$child->d(); // null: the class's own `@method` comes first

A mixin's @methods are only used through a __call(), and its @propertys through a __get(): those of the class, or of the mixin when the class is an interface.

Psalm-specific tags#

There are a number of custom tags that determine how Psalm treats your code.

@psalm-consistent-constructor#

See UnsafeInstantiation

@psalm-consistent-templates#

See UnsafeGenericInstantiation

@param-out, @psalm-param-out#

This is used to specify that a by-ref type is different from the one that entered. In the function below the first param can be null, but once the function has executed the by-ref value is not null.

<?php
/**
 * @param-out string $s
 */
function addFoo(?string &$s) : void {
    if ($s === null) {
        $s = "hello";
    }
    $s .= "foo";
}

@param-closure-this, @psalm-param-closure-this, @phpstan-param-closure-this#

This binds $this to a specific class type inside a Closure or arrow-function expression passed directly as an argument. Use it when the receiving function or method runs the callback with Closure::bind / Closure::call so that $this resolves to a different object than the caller's $this. The bound type may be a class name (including a generic type such as Box<int>), $this, static, self, parent, or a class-level template parameter.

<?php
class Macroable {
    /**
     * @param-closure-this static $macro
     */
    public static function macro(string $name, Closure $macro): void {
        // store $macro and later run $macro->call($instance)
    }
}

class Builder extends Macroable {
    public int $value = 42;
}

Builder::macro('grab', function (): int {
    // $this is Builder here, not the outer scope
    return $this->value;
});

Inside the callback, class scope follows the bound type: self:: refers to that class and parent:: to its parent. Property types retain the bound class's generic arguments rather than using the caller's property types.

The tag is ignored when it cannot name one known class to bind to (a union such as A|B, or a class Psalm has not seen), and when the argument is a static closure, since PHP cannot rebind one.

@psalm-var, @psalm-param, @psalm-return, @psalm-property, @psalm-property-read, @psalm-property-write, @psalm-method#

When specifying types in a format not supported by phpDocumentor (but supported by Psalm) you may wish to prepend @psalm- to the PHPDoc tag, so as to avoid confusing your IDE. If a @psalm-prefixed tag is given, Psalm will use it in place of its non-prefixed counterpart.

@psalm-ignore-var#

This annotation is used to ignore the @var annotation written in the same docblock. Some IDEs don't fully understand complex types like generics. To take advantage of such IDE's auto-completion, you may sometimes want to use explicit @var annotations even when psalm can infer the type just fine. This weakens the effectiveness of type checking in many cases since the explicit @var annotation overrides the types inferred by psalm. As psalm ignores the @var annotation which is co-located with @psalm-ignore-var, IDEs can use the type specified by the @var for auto-completion, while psalm can still use its own inferred type for type checking.

<?php
/** @return iterable<array-key,\DateTime> $f */
function getTimes(int $n): iterable {
    while ($n--) {
        yield new \DateTime();
    }
};
/**
 * @var \Datetime[] $times
 * @psalm-ignore-var
 */
$times = getTimes(3);
// this trace shows "iterable<array-key, DateTime>" instead of "array<array-key, Datetime>"
/** @psalm-trace $times */
foreach ($times as $time) {
    echo $time->format('Y-m-d H:i:s.u') . PHP_EOL;
}

@psalm-suppress SomeIssueName#

This annotation is used to suppress issues. It can be used in function docblocks, class docblocks and also inline, applying to the following statement.

Function docblock example:

<?php
/**
 * @psalm-suppress PossiblyNullOperand
 */
function addString(?string $s) {
    echo "hello " . $s;
}

Inline example:

<?php
function addString(?string $s) {
    /** @psalm-suppress PossiblyNullOperand */
    echo "hello " . $s;
}

@psalm-suppress all can be used to suppress all issues instead of listing them individually.

Suppressing an unused-code issue (such as UnusedClass or PossiblyUnusedMethod) only silences the report for that symbol — it does not mark the symbol as used, so code that is only referenced from it is still reported as unused. Redundant @psalm-suppress annotations, in any docblock (including on classes, interfaces, traits and enums), are reported by --find-unused-psalm-suppress.

@psalm-assert, @psalm-assert-if-true, @psalm-assert-if-false, @psalm-if-this-is and @psalm-this-out#

See Adding assertions.

@psalm-ignore-nullable-return#

This can be used to tell Psalm not to worry if a function/method returns null. It’s a bit of a hack, but occasionally useful for scenarios where you either have a very high confidence of a non-null value, or some other function guarantees a non-null value for that particular code path.

<?php
class Foo {}
function takesFoo(Foo $f): void {}

/** @psalm-ignore-nullable-return */
function getFoo(): ?Foo {
  return rand(0, 10000) > 1 ? new Foo() : null;
}

takesFoo(getFoo());

@psalm-ignore-falsable-return#

This provides the same, but for false. Psalm uses this internally for functions like preg_replace, which can return false if the given input has encoding errors, but where 99.9% of the time the function operates as expected.

@psalm-seal-properties, @psalm-no-seal-properties, @seal-properties, @no-seal-properties#

If you have a magic property getter/setter, you can use @psalm-seal-properties to instruct Psalm to disallow getting and setting any properties not contained in a list of @property (or @property-read/@property-write) annotations. This is automatically enabled with the configuration option sealAllProperties and can be disabled for a class with @psalm-no-seal-properties

<?php
/**
 * @property string $foo
 * @seal-properties
 */
class A {
     public function __get(string $name): ?string {
          if ($name === "foo") {
               return "hello";
          }
     }

     public function __set(string $name, $value): void {}
}

$a = new A();
$a->bar = 5; // this call fails

@method overloads#

A magic method can have several @method (or @psalm-method) lines of the same name: Psalm uses the first one whose parameters accept the arguments of the call, or reports the issues against the last one when none does. A @psalm-method of a name replaces the @methods of that name.

<?php
final class LimitedQuery {}
final class UnlimitedQuery {}
final class PagedResult { public function getPageCount(): int { return 1; } }
final class PlainResult { public function getAllRecords(): array { return []; } }

/**
 * @method PagedResult search(LimitedQuery $query)
 * @method PlainResult search(UnlimitedQuery $query)
 * @method int count(string $table)
 * @method string count(int $table, int $limit)
 */
class Searcher {
    public function __call(string $name, array $args): mixed {
        throw new BadMethodCallException($name);
    }
}

$searcher = new Searcher();
$searcher->search(new LimitedQuery())->getPageCount();   // no issue
$searcher->search(new LimitedQuery())->getAllRecords();  // UndefinedMethod
$searcher->search(new UnlimitedQuery())->getAllRecords(); // no issue
$searcher->count("users");                                // int
$searcher->count(1, 2);                                   // string
$searcher->count(1.5);                                    // InvalidArgument, TooFewArguments

@psalm-overload#

Declares one signature a function or method can be called with, for one whose behaviour depends on the arguments. A call is checked against the first @psalm-overload whose parameters accept its arguments (by position and by name), or, when none does, against its own signature if that accepts them (an int|string argument for separate int and string overloads), else against the last overload. A first-class callable (search(...)) has the own signature. A method that overrides one with overloads has its own signature unless it declares the overloads again. Not supported yet: constructors.

<?php
/**
 * @psalm-overload (LimitedQuery $query): PagedResult
 * @psalm-overload (UnlimitedQuery $query): PlainResult
 */
function search(Query $query): Result {
    // ...
}

search(new LimitedQuery())->getPageCount();    // no issue
search(new LimitedQuery())->getAllRecords();   // UndefinedMethod
search(new UnlimitedQuery())->getAllRecords(); // no issue

/** @var LimitedQuery|UnlimitedQuery $query */
search($query);                                // Result, from the function's own signature

class Repository {
    /**
     * @psalm-overload (string $id): int
     * @psalm-overload (int $id): string
     */
    public static function find(string|int $id): int|string {
        // ...
    }
}

Repository::find("a"); // int
Repository::find(1);   // string

An overload has to fit the signature: the same parameter names at the same positions, and types the signature accepts. By-reference comes from the signature.

<?php
/**
 * @psalm-overload (int $value): int
 * @psalm-overload (string $other): string
 */
function pick(int|string $value): int|string { // InvalidDocblock: $other is at the position of $value
    return $value;
}

@psalm-seal-methods, @psalm-no-seal-methods, @seal-methods, @no-seal-methods#

If you have a magic method caller, you can use @psalm-seal-methods to instruct Psalm to disallow calling any methods not contained in a list of @method annotations. This is automatically enabled with the configuration option sealAllMethods and can be disabled for a class with @psalm-no-seal-methods

<?php
/**
 * @method foo(): string
 * @seal-methods
 */
class A {
     public function __call(string $name, array $args) {
          if ($name === "foo") {
               return "hello";
          }
     }
 }

$a = new A();
$b = $a->bar(); // this call fails

@psalm-stub-override#

Used in a stub file on a class, interface, trait or method that is meant to replace an existing declaration. Psalm stops with an error if there is nothing to replace, so a stub cannot silently go stale (a renamed class, a wrong namespace, a removed method).

<?php
// stub file
/** @psalm-stub-override */
class ArrayObject {
    /** @psalm-stub-override */
    public function count(): int {} // fine: ArrayObject::count() exists

    /** @psalm-stub-override */
    public function nope(): int {} // error: ArrayObject::nope is marked as stub override, but no original counterpart found
}

@psalm-internal#

Used to mark a class, property or function as internal to a given namespace or class or even method. Psalm treats this slightly differently to the PHPDoc @internal tag. For @internal, an issue is raised if the calling code is in a namespace completely unrelated to the namespace of the calling code, i.e. not sharing the first element of the namespace.

In contrast for @psalm-internal, the docblock line must specify a namespace. An issue is raised if the calling code is not within the given namespace.

<?php
namespace A\B {
    /**
     * @internal
     * @psalm-internal A\B
     */
    class Foo { }
}

namespace A\B\C {
    class Bat {
        public function batBat(): void {
            $a = new \A\B\Foo(); // this is fine
        }
    }
}

namespace A {
    class B {
        public function batBat(): void {
            $a = new \A\B\Foo(); // this is fine
        }
    }
}

namespace A\C {
    class Bat {
        public function batBat(): void {
            $a = new \A\B\Foo(); // error
        }
    }
}

namespace X {
    class Foo {        
        /**
         * @psalm-internal Y\Bat::batBat
         */
        public static function barBar(): void {
        }
    }
}

namespace Y {
    class Bat {
        public function batBat() : void {
            \X\Foo::barBar(); // this is fine
        }
        public function fooFoo(): void {
            \X\Foo::barBar(); // error
        }
    }
}

The code a project doesn't ship is internal without the annotation: classes that only composer.json's autoload-dev loads, files that .gitattributes leaves out of the package with export-ignore, and, with psalm/plugin-phpunit, the test suites of phpunit.xml and the test cases. It is internal to the root namespaces of all that code, so test code may use the test code of another namespace. Code in the global namespace can't be internal.

<?php
namespace Lib\Tests { // autoload-dev: "Lib\\Tests\\": "tests/"
    final class Helper {}
}

namespace Lib {
    new Tests\Helper(); // this is fine
}

namespace Other {
    new \Lib\Tests\Helper(); // InternalClass
}

@psalm-readonly and @readonly#

Used to annotate a property that can only be written to in its defining class's constructor.

<?php
class B {
  /** @readonly */
  public string $s;

  public function __construct(string $s) {
    $this->s = $s;
  }
}

$b = new B("hello");
echo $b->s;
$b->s = "boo"; // disallowed

Purity and capabilities#

Psalm tracks the side effects a function, method or closure may have as a set of capabilities: read-props, write-this-props, write-props, read-globals, write-globals, write-refs, io and time, with pure for none of them and impure for all of them. The Purity Model explains what each capability allows, how calls are charged and how purity templates work. The annotations are listed below.

@psalm-pure and @psalm-impure#

@psalm-pure on a function or method gives it no capabilities: its result depends only on its arguments. On a class, it applies to every method and bans the use of properties. @psalm-impure on a function or method gives it every capability, the default for unannotated code, written out. See Annotations.

@psalm-capabilities#

@psalm-capabilities <set> on a function, method or closure gives the capabilities it may use, separated by | or commas, as in @psalm-capabilities read-props|write-this-props. The set may be a type alias. On a class or interface, it is a contract for every method of the class and of the classes extending or implementing it. See Capabilities.

@psalm-immutable#

Used to annotate a class where every property is treated by consumers as @psalm-readonly and every instance method is treated as @psalm-capabilities read-props (see Annotations).

<?php
/**
 * @psalm-immutable
 */
abstract class Foo
{
    public string $baz;

    abstract public function bar(): int;
}

/**
 * @psalm-immutable
 */
final class ChildClass extends Foo
{
    public function __construct(string $baz)
    {
        $this->baz = $baz;
    }

    public function bar(): int
    {
        return 0;
    }
}

$anonymous = new /** @psalm-immutable */ class extends Foo
{
    public string $baz = "B";

    public function bar(): int
    {
        return 1;
    }
};

@psalm-mutable#

Used to annotate a class where at least one property is mutable: this is the default behavior, but it can be explicitly marked for clarity.

@psalm-purity-template#

@psalm-purity-template P on a class, function or method declares a purity template: a template parameter whose values are capability sets rather than types. It is used as the purity of a callable (Closure[P](int): int) or as the purity argument of a class (Box[P]<int>, @extends Box[pure]). Bounds and a default are written as a chain, @psalm-purity-template lower <= P(default) <= upper, and Closure[_](...) in a @param type declares an unnamed one. See Purity templates.

Iterators and generators#

Traversable, Iterator, IteratorAggregate, Generator and iterable have a purity template, TPurity: what iterating over them may do, as in Iterator[pure]<int, string> or iterable[pure]<int, string> (impure by default). See Iterators and generators.

@psalm-purity-from-template#

@psalm-purity-from-template P on a function or method: each call needs the function-like's own capabilities plus whatever P, a purity template or a type template bound to a closure type, is bound to at that call. See @psalm-purity-from-template.

@psalm-allow-private-mutation#

Used to annotate readonly properties that can be mutated in a private context. With this, public properties can be read from another class but only be mutated within a method of its own class.

<?php
class Counter {
  /**
   * @readonly
   * @psalm-allow-private-mutation
   */
  public int $count = 0;

  public function increment() : void {
    $this->count++;
  }
}

$counter = new Counter();
echo $counter->count; // outputs 0
$counter->increment(); // Method can mutate property
echo $counter->count; // outputs 1
$counter->count = 5; // This will fail, as it's mutating a property directly

@psalm-readonly-allow-private-mutation#

This is a shorthand for the property annotations @readonly and @psalm-allow-private-mutation.

<?php
class Counter {
  /**
   * @psalm-readonly-allow-private-mutation
   */
  public int $count = 0;

  public function increment() : void {
    $this->count++;
  }
}

$counter = new Counter();
echo $counter->count; // outputs 0
$counter->increment(); // Method can mutate property
echo $counter->count; // outputs 1
$counter->count = 5; // This will fail, as it's mutating a property directly

@psalm-trace#

You can use this annotation to trace inferred type (applied to the next statement).

<?php

/** @psalm-trace $username */
$username = $_GET['username']; // prints something like "test.php:4 $username: mixed"

Note: it throws special low-level issue. To see it, you can set the global errorLevel to 1, or invoke Psalm with --show-info=true, but both these solutions will probably result in a lot of output. Another solution is to selectively bump the error level of the issue, so that you only get one more error:

<!-- psalm.xml -->
<issueHandlers>
  <Trace errorLevel="error"/>
</issueHandlers>

@psalm-check-type#

You can use this annotation to ensure the inferred type matches what you expect.

<?php

/** @psalm-check-type $foo = int */
$foo = 1; // No issue

/** @psalm-check-type $bar = int */
$bar = "not-an-int"; // Checked variable $bar = int does not match $bar = 'not-an-int'

@psalm-check-type-exact#

Like @psalm-check-type, but checks the exact type of the variable without allowing subtypes.

<?php

/** @psalm-check-type-exact $foo = int */
$foo = 1; // Checked variable $foo = int does not match $foo = 1

@psalm-taint-*#

See Security Analysis annotations.

@psalm-type#

This allows you to define an alias for another type.

<?php
/**
 * @psalm-type PhoneType = array{phone: string}
 */
class Phone {
    /**
     * @psalm-return PhoneType
     */
    public function toArray(): array {
        return ["phone" => "Nokia"];
    }
}

@psalm-import-type#

You can use this annotation to import a type defined with @psalm-type if it was defined somewhere else.

<?php
/**
 * @psalm-import-type PhoneType from Phone
 */
class User {
    /**
     * @psalm-return PhoneType
     */
    public function toArray(): array {
        return array_merge([], (new Phone())->toArray());
    }
}

You can also alias a type when you import it:

<?php
/**
 * @psalm-import-type PhoneType from Phone as MyPhoneTypeAlias
 */
class User {
    /**
     * @psalm-return MyPhoneTypeAlias
     */
    public function toArray(): array {
        return array_merge([], (new Phone())->toArray());
    }
}

@psalm-require-extends#

The @psalm-require-extends annotation allows you to define the requirements that a trait imposes on the using class.

Psalm also reads the @phpstan-require-extends spelling. When a docblock has both, @psalm-require-extends is used.

<?php
abstract class DatabaseModel {
  // methods, properties, etc.
}

/**
 * @psalm-require-extends DatabaseModel
 */
trait SoftDeletingTrait {
  // useful but scoped functionality, that depends on methods/properties from DatabaseModel
}


class MyModel extends DatabaseModel {
  // valid
  use SoftDeletingTrait;
}

class NormalClass {
  // triggers an error
  use SoftDeletingTrait;
}

@psalm-require-implements#

Behaves the same way as @psalm-require-extends, but for interfaces.

Psalm also reads the @phpstan-require-implements spelling. When a docblock has both, only the @psalm-require-implements tags are used.

@no-named-arguments#

This will prevent access to the function or method tagged with named parameters (by emitting a NamedArgumentNotAllowed issue).

Incidentally, it will change the inferred type for the following code:

<?php
    function a(int ...$a){
        var_dump($a);
    }

The type of $a is array<array-key, int> without @no-named-arguments but becomes list<int> with it, because it excludes the case where the offset would be a string with the name of the parameter

This annotation can also be used in the docblock of a class, an interface, a trait or an enum. It then applies to all the methods of that class, unless a method has @arguments-by-name, @optional-arguments-by-name or @stable-parameter-names.

@optional-arguments-by-name#

Callers must pass the arguments of optional parameters (the ones that have a default value) by name. Psalm emits a PositionalArgumentNotAllowed issue when such an argument is passed by position.

The names of optional parameters are stable, but not their order. An optional parameter can be added, moved or removed without breaking callers. For required parameters, the order is stable and the names are not.

<?php
final class Configuration
{
    /**
     * @optional-arguments-by-name
     */
    public function __construct(
        string $dialect,
        array $groups = [],
        bool $allowExtraAttributes = true,
    ) {
    }
}

new Configuration('openapi-3.1', groups: ['read']); // OK
new Configuration('openapi-3.1', ['read']); // PositionalArgumentNotAllowed

This annotation, @arguments-by-name and @stable-parameter-names can also be used in the docblock of a class, an interface, a trait or an enum. They then apply to the public and protected methods of that class. In a trait, they apply to private methods too, because the classes that use the trait can call them. A tag on a method replaces the tag on the class. A method that overrides or implements a tagged method keeps the tag of the parent method, unless the overriding method declares another tag. These annotations can't be combined with each other, nor with @no-named-arguments. They also apply to @internal code when allowInternalNamedArgumentCalls is false.

Variadic parameters are not affected. But a variadic parameter gets arguments passed by position only when the parameters before it are passed by position too. When one of these parameters must be passed by name, the type of ...$args is array<string, T> instead of array<array-key, T>.

When arguments are unpacked from an array, integer keys are passed by position and string keys are passed by name.

@arguments-by-name#

Callers must pass all arguments by name, except the ones of variadic parameters. Psalm emits a PositionalArgumentNotAllowed issue for each argument passed by position.

Parameter names are stable, but not their order. See @optional-arguments-by-name for where this annotation can be used.

@stable-parameter-names#

Callers can pass arguments by name or by position. Both the names and the order of the parameters are stable. Psalm doesn't report anything at call sites.

A method that overrides a method with this annotation and renames a parameter is reported as ParamNameMismatch, even when allowNamedArgumentCalls is false. See @optional-arguments-by-name for where this annotation can be used.

@psalm-ignore-variable-property and @psalm-ignore-variable-method#

Instructs Psalm to ignore variable property fetch / variable method call when looking for dead code.

class Foo
{
    // this property can be deleted by Psalter,
    // as potential reference in get() is ignored
    public string $bar = 'bar';

    public function get(string $name): mixed
    {
        /** @psalm-ignore-variable-property */
        return $this->{$name};
    }
}

When Psalm encounters variable property, it treats all properties in given class as potentially referenced. With @psalm-ignore-variable-property annotation, this reference is ignored.

While PossiblyUnusedProperty would be emitted in both cases, using @psalm-ignore-variable-property would allow Psalter to delete Foo::$bar.

@psalm-ignore-variable-method behaves the same way, but for variable method calls.

@psalm-yield#

Used to specify the type of value which will be sent back to a generator when an annotated object instance is yielded.

<?php
/**
 * @template-covariant TValue
 * @psalm-yield TValue
 */
interface Promise {}

/**
 * @template-covariant TValue
 * @template-implements Promise<TValue>
 */
class Success implements Promise {
    /**
     * @psalm-param TValue $value
     */
    public function __construct($value) {}
}

/**
 * @return Promise<string>
 */
function fetch(): Promise {
    return new Success('{"data":[]}');
}

function decode(): Generator {
    $data = yield fetch();

    // this is fine, Psalm knows that $data is a string
    return json_decode($data);
}

Psalm only reads the types: at runtime a coroutine runner (for instance the one of amphp or Revolt) has to resume the generator with the value of the yielded object.

This annotation supports only generic types, meaning that e.g. @psalm-yield string would be ignored.

@api, @psalm-api#

Used to tell Psalm that a class or method is used, even if no references to it can be found. Unused issues will be suppressed.

For example, in frameworks, controllers are often invoked "magically" without any explicit references to them in your code. You should mark these classes with @psalm-api.

/**
 * @psalm-api
 */
class UnreferencedClass {}

When an Unused* issue is reported, there are only two correct fix paths:

  • The symbol is genuinely public surface — consumed from outside the analysed codebase, e.g. a library entry point, or a class instantiated only by a framework, container or plugin loader. Mark it with @api/@psalm-api. Use this only for real public surface.
  • Otherwise the symbol is dead code — remove it, along with anything that was only reachable through it.

For a reported method or property, @api may be placed either on that member or on the whole class, but marking the whole class is almost always the right choice: an externally-consumed member belongs to an externally-consumed class, and one class-level annotation then covers its entire public API. Conversely, if a member is reported as unused inside a class that is not marked @api, it is almost always genuinely dead code — remove it rather than annotating the lone member. Annotating an individual member is only correct in the uncommon case where the class is not public API but that one member genuinely is.

A class that implements an interface (or extends a class) defined outside the project is treated as public surface automatically, since it can be instantiated and invoked through that external type: its overriding methods are considered used without an explicit @api.

A library can make unused-code detection treat all of its code that isn't @internal as @api with markAllNonInternalCodeAsApi, at the cost of unused-code detection for internal code that lacks @internal.

Do not reach for @psalm-suppress UnusedClass (or another Unused* suppression) in place of @api: as noted above, a suppression only silences the report, it does not mark the symbol as used, so symbols it references may still be reported as unused.

@psalm-inheritors#

Used to tell Psalm that a class can only be extended by a certain subset of classes.

For example,

<?php
/**
 * @psalm-inheritors FooClass|BarClass
 */
class BaseClass {}
class FooClass extends BaseClass {}
class BarClass extends BaseClass {}
class BazClass extends BaseClass {} // this is an error

Psalm also reads the @phpstan-sealed spelling. When a docblock has both, only the @psalm-inheritors tags are used.

Type Syntax#

Psalm supports PHPDoc’s type syntax, and also the proposed PHPDoc PSR type syntax.

A detailed write-up is found in Typing in Psalm