为什么我在视图中显示控制器数组中未定义变量得到错误


why I am getting error undefined variable in display controller array in view?

我的控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class VerifyAppointment extends CI_Controller {
    function __construct()
    {
        parent::__construct();

        $this->load->model('appointment_model','',TRUE);
    }
    function index()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('rdatetimepicker', 'Appointment date', 'trim|required|xss_clean');
        if($this->form_validation->run() == FALSE)
        {
            $this->load->view("pages/appointment");
        }
        else
        {
            $this->appointment_model->insert();
            $data['posts'] = "hih";
            $this->load->view('pages/appointment',$data);
        }
    }
}

我的观点:

<?php
    echo $posts;
?>

你得到错误,因为视图不得到$posts时验证条件是false你初始化$data['posts']="";在开始或在每个条件根据你的编码风格

 function index()
        {
            $this->load->library('form_validation');
        $this->form_validation->set_rules('rdatetimepicker', 'Appointment date', 'trim|required|xss_clean');
        if($this->form_validation->run() == FALSE)
        {
           $data['posts']="";  //declare posts here              
          $this->load->view('pages/appointment',$data);
        }
        else
        {
            $this->appointment_model->insert();
            $data['posts'] = "hih";
            $this->load->view('pages/appointment',$data);
        }
    }

或者你可以在view之前检查array,像这样;如果你不想更改控制器

<?php
    if(isset($posts))
    echo $posts;
?>