LoginSignup
0
0

More than 1 year has passed since last update.

property_exists()でstatic|selfを使う

Last updated at Posted at 2021-11-29

はじめに

静的クラス(関数)で自身のクラスのプロパティが存在するか調べたい、という願いを叶える記事です。

解決

普通に書くとこうなります。

ダメな例
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は色々なところで使われます。もし躓くことがあれば、また思い出してみてください。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0