2017-10-28 2 views
1

に使用こんにちは、私は私が他のクラス における非静的メソッドを作成するとき、私は問題を発見する方法コントローラLaravel - どのように私は、インスタンスを新たにし、任意のコントローラメソッド

のいずれかの方法のための新しいグローバルオブジェクトに知りたいとそれらを使用するときは、どのメソッドでも新しいインスタンスを作成する必要があります。

<?php 

    namespace App\Http\Controllers; 

    use DB; 
    use App\Article; 
    use Illuminate\Http\Request; 
    use App\Custom_Class\Schedule; 


    class ArticleController extends Controller 
    { 

    // $schedule_obj = new Schedule(); //Try this outside method but not work 
     public function index() 
     { 

      $schedule_obj = new Schedule(); 
      $schedule_obj->sayHi(); 


     } 
     public function someAction() 
     { 
      $schedule_obj = new Schedule(); //I do not want to new instance again. 
      $schedule_obj->sayHi(); 
     } 
+2

を使用することができます。 – Rits

答えて

1

あなたのコンストラクタに新しいScheduleインスタンスを開始し、プライベートクラス全体の変数に割り当てることができます。その後、すべての方法で単一のScheduleインスタンスにアクセスできます。あなたがアプリケーションスコープでそれを持っているしたい場合は、コントローラ内部

class ArticlesController extends Controller 
{ 
    /** @var Schedule Instance of the Schedule class. */ 
    private $schedule; 

    /** 
    * ArticlesController constructor. 
    */ 
    public function __construct() 
    { 
     $this->schedule = new Schedule(); 
    } 

    /** 
    * Does the #index() method thing. 
    */ 
    public function index() 
    { 
     $this->schedule->sayHi(); 
    } 
} 
1

あなたはユーザー__construct方法が、あなたは、コンストラクタでそれを行うLaravel singletonパターン

関連する問題