はじめに
静的クラス(関数)で自身のクラスのプロパティが存在するか調べたい、という願いを叶える記事です。
解決
普通に書くとこうなります。
ダメな例
public static function existsFoo() {
return property_exists(static, 'foo');
}
しかし、この状態だとこんなエラーが出ます。
syntax error, unexpected token ",", expecting ":"
もう答えは書いてありますが、さっぱりわからない、という方もいると思います。
まずは、正解をご覧ください。
正解例
public static function existsFoo() {
return property_exists(static::class, 'foo');
}
static
に::class
を付け加えました。
::classとは
class キーワードでもクラス名の解決を行うことが出来ます。 クラスの名前が ClassName になっているクラスの完全修飾名を取得するには、 ClassName::class を使います。
要するに、クラスの名前解決をしてエラーを取り除きますよーという優れものです。
また、property_exists()
についても少しみてみます。
function property_exists($object_or_class, string $property): bool { }
@param object|string $object_or_class
The class name or an object of the class to test for
@param string $property — The name of the property
@return bool
第一引数の$object_or_class
の型に注目です。object|string
とありますね。今回のケースではstring
型になっています。
終わりに
このstatic::class
は色々なところで使われます。もし躓くことがあれば、また思い出してみてください。