class-string型
静的解析ツールに実装された独自の型。基本的にはPHPDocに書くことで用いる。
#Psalmの型 #PHPStanの型 #Phanの型 #PhpStormの型
PsalmとPHPStanの実装ではジェネリクスを組み合わせることができる。
マニュアル
Psalm
of のサポートあり
https://psalm.dev/docs/annotating_code/type_syntax/scalar_types/#class-string-interface-string
PHPStan
of のサポートあり
https://phpstan.org/writing-php-code/phpdoc-types#class-string
Phan
of のサポートなし
https://github.com/phan/phan/pull/2250
PhpStorm
2021.2(Beta) 以降でサポート
of のサポートなし
PhpStorm 2021.2 Beta: Generics Support Is Coming | The PhpStorm Blog
stringからclass-string型をつける方法
is_a()関数の第2引数に名前空間付きクラス名を渡し、第3引数にtrueを渡すと判定できます
code:php
<?php declare(strict_types = 1);
function f(string $class): void {
\PHPStan\dumpType($class); // Dumped type: string
// if 文の中では class-string<Exception> として扱われる
if (is_a($class, Exception::class, true)) {
\PHPStan\dumpType($class); // Dumped type: class-string<Exception>
}
// アサーションすると、これ以降はは class-string<Exception> として扱われる
assert(is_a($class, Exception::class, true));
// コメントでもPHPStanに型を認識させられない
/** @var class-string<\Throwable> $class */
}