いろいろやり方あると思いますが、自分ならこうするかなという実装を書いておきます。
Cardクラス
php
1<?php
2class Card {
3 public $name = '';
4
5 function __construct(string $name) {
6 $this->name = $name;
7 }
8}
CardRegistryクラス
Card
クラスのインスタンスを管理するためのクラスです。
外部からは$cardList
を直接参照せず、getByKey
やgetRandom
やlistAll
などアクセス用関数をここに定義すると使い勝手が良いです。
php
1<?php
2require_once './card.php';
3
4class CardRegistry {
5 private static $_shared = null;
6
7 public $cardList = [];
8
9 private function __construct() {
10 $this->cardList = [
11 'a' => new Card('a'),
12 'b' => new Card('b'),
13 ];
14 }
15
16 public static function getSharedInstance() {
17 if (!(self::$_shared instanceof CardRegistry)) {
18 self::$_shared = new CardRegistry();
19 }
20
21 return self::$_shared;
22 }
23}
index.php
CardRegistry
のシングルトンインスタンスを使用して、Card
のリストを読み込んで表示しています。
php
1<?php
2require_once './card_registry.php';
3
4$cardRegistry = CardRegistry::getSharedInstance();
5?>
6
7<table>
8 <tbody>
9 <?php foreach ($cardRegistry->cardList as $key => $card): ?>
10 <tr>
11 <th>
12 <?= $key ?>
13 </th>
14
15 <td>
16 <?= $card->name ?>
17 </td>
18 </tr>
19 <?php endforeach; ?>
20 </tbody>
21</table>