LoginSignup
1
1

More than 5 years have passed since last update.

PHPで定数のリストが定義されたクラスからランダムに定数を取得する

Posted at

テスト用のデータを作成する際に、ランダムにカテゴリーが入るようにしたかったので、どのようにクラスから定義を取得すれば良いのか調べました。

ファイル構成

定数が定義されているクラス

<?php

namespace App\Constants;

class Categories
{
    const Category1 = 'category1';
    const Category2 = 'category2';
    const Category3 = 'category3';
}

テストデータを作成する呼び出し元(適当)

<?php

namespace App

class HogeSeeder
{
    public function hoge()
    {
        $reflect = new ReflectionClass('App\Constants\Categories');
        $categories = array_values($reflect->getConstants());

        // これでランダムに取得できるので、データ作成時にこのカテゴリーを使用する
        var_dump($categories[random_int(0, count($categories) - 1)]);
    }
}

解説

reflectionクラスを使用することで、対象クラスのあれこれを取得できます。
ReflectionClass クラス

reflectionクラスのgetConstantsを使用することで、そのクラスに定義されている定数を取得を配列として取得できました。

dump($reflect->getConstants());

array:3 [
  "CATEGORY1" => "inappropriate category 1"
  "CATEGORY2" => "inappropriate category 2"
  "CATEGORY3" => "inappropriate category 3"
]

array_values で数値添字にした上でrandom_intでランダムに数値を取得することでランダムにカテゴリーを取得できました。

dump(array_values($reflect->getConstants()));

array:3 [
  0 => "inappropriate category 1"
  1 => "inappropriate category 2"
  2 => "inappropriate category 3"
]
1
1
0

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
1
1