0

admin.phpコントローラーに次のようなものがあります。

function __construct()
{
    parent::__construct();
    if (!$this->session->userdata('logged_in_admin') )
    {
        redirect('admin/login');
    }
    $this->load->model('mdl_admin');
    $data['my_test_variable'] = "This is test!";
}

public function index()
{
    $data['header'] = "Home";
    $this->load->view('admin_frontpage', $data);
}

そして私の見解では、これは:

<?php echo $header; ?>
<?php echo $my_test_variable; ?>

ただし、ヘッダー変数のみがエコーされます。ビュー ファイルに送信される $data 配列にmy_test_variableも含まれている場合でも。

何故ですか?

私は何を間違っていますか?

私が試しても:

    $this->data['my_test_variable'] = "This is test!";

動作していません。

4

3 に答える 3

2

ただし、$dataビューに送信される配列には含まれていませmy_test_variableん。関数ではindex()、ビューに送信するときにその値を設定していません。

では__construct()、関数$data内でのみ表示されるローカル変数です。__construct()関数の外部、おそらく関数内でアクセスしたい場合index()、1 つのオプションはそれをインスタンス プロパティにすることです。

たとえば、 の代わりに を$data['my_test_variable']使用できます$this->data['my_test_variable']。次に、index()の代わりに を$data使用できます$this->data

于 2013-03-08T13:47:43.790 に答える
1

まず第一に、暗黙のうちに PHP で変数を作成しています。これは悪い習慣です。存在しない変数に配列キーを設定しないでください。適切なエラー報告設定が有効になっていると、これが問題の原因になります。

それでは、まず、その問題を修正しましょう。

function __construct() {
    parent::__construct();

    if (!$this->session->userdata('logged_in_admin')) {
        redirect('admin/login');
    }

    $this->load->model('mdl_admin');

    $data = array();
    $data['my_test_variable'] = "This is test!";
}

public function index() {
    $data = array();
    $data['header'] = "Home";
    $this->load->view('admin_frontpage', $data);
}

そうすることで、今の自分の問題が見えてくるはずだと思います。__construct()メソッドとメソッドはindex()、別のスタックで実行されます。つまり、一方の内部で宣言した変数は、他方では使用できないということです。これを機能させるには、次のように、作成しているクラスのインスタンス変数を利用する必要があります。

class MyView {
    protected $data = array();

    function __construct() {
        parent::__construct();

        if (!$this->session->userdata('logged_in_admin')) {
            redirect('admin/login');
        }

        $this->load->model('mdl_admin');
        $this->data['my_test_variable'] = "This is test!";
    }

    public function index() {
        $this->data['header'] = "Home";
        $this->load->view('admin_frontpage', $this->data);
    }
}

そして今、あなたはあなたが求めているものを手に入れるべきです

于 2013-03-08T13:47:25.260 に答える