cakephp3でCollectionディレクトリにあるtraitの呼び出しでcall to undefined methodとなっております。
php
1namespace App\Controller; 2use Cake\Network\Exception\NotFoundException; 3use Cake\Event\Event; 4use App\Collection\TraitSingleton; 5class TestsController extends AppController { 6public function initialize() 7 { 8 parent::initialize(); 9 10 } 11 12 public function index() { 13 $obj = TestsController::getInstance();//ここでエラー 14 } 15}
シングルトン実装はteratailでもお世話になってます、ファガイさんの記事のを使わせてもらいました。
php
1trait TraitSingleton 2{ 3 /** 4 * get instance. 5 */ 6 public static function getInstance() { 7 static $instance; // 静的なinstanceを保持するための変数 8 9 // インスタンスが存在しない時だけインスタンスを作る 10 if(! $instance) 11 { 12 // 遅延静的束縛 13 $reflection = new ReflectionClass(get_called_class()); 14 $construct = $reflection->getConstructor(); 15 $construct->setAccessible(true); 16 17 // インスタンスをコンストラクタ無しで作成 18 $instance = $reflection->newInstanceWithoutConstructor(); 19 20 // コンストラクタを実行する 21 $construct->invokeArgs($instance ,func_get_args()); 22 } 23 24 return $instance; 25 } 26/** 27 * the instance clone is not allowd 28 * @throws RuntimeException 29 */ 30 public final function __clone() 31 { 32 throw new RuntimeException('Clone is not allowed against ' . get_called_class($this)); 33 }
どのように呼び出せばgetInstance()が使えますでしょうか。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。