在CodeIgniter中的函数外声明一个变量 [英] Declaring a variable outside a function in CodeIgniter

查看:92
本文介绍了在CodeIgniter中的函数外声明一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触CodeIgniter。我试图在点击提交后再次输出一个视图,但视图有一个变量从控制器,但当我尝试它,它不工作。

I'm new to CodeIgniter. I'm trying to output a view again after clicking a submit but the view has a variable from the controller, but when I tried it, it doesn't work.

<?php
    class Site extends CI_Controller{

        public $data1['value'] = "What to insert";

        public function index(){
            $this->load->view('home',$this->data1);
        }

    public function get_product(){
            $data = array(
                'product_name' => $this->input->post('prod_name')
            );
            $this->site_model->insert_product($data);
            $this->load->view('home',$this->data1);
        }

    }
?>

以下是我的观点:

<div id="container">
<h1><?php echo $data1;?></h1>

    <?php echo form_open('site/get_product'); ?>

    <p>
        <label for="product">Product Name </label>
        <input type="text" id="product" name="prod_name" />
    </p>    

    <input type="submit" name="submit_but" value="submit">

<?php echo form_close(); ?>

</div>

get_product 视图,但我知道如果我要在函数中再次声明它将是一个麻烦。

In get_product I need to call again the view but I know it'll be such a hassle if I'm going to declare it again inside the function.

错误:

Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\xampp\htdocs\code_igniter\application\controllers\site.php on line 9


推荐答案

__ construct函数在每次运行脚本时都会调用,因此您可以在此函数中添加常量值以用于视图或其他用法。

__construct function is calling every time you run the script so you can add your constant values in this function for view or other usage.

<?php
class Site extends CI_Controller{
    public $data1 = array();

    public function __construct() {
        $this->data1['value'] = "bla bla";
    }

    public function index(){
        $this->load->view('home',$this->data1);
    }

    public function get_product(){
        $data = array(
        'product_name' => $this->input->post('prod_name')
        );
        $this->site_model->insert_product($data);
        $this->load->view('home',$this->data1);
    }
}
?>

这篇关于在CodeIgniter中的函数外声明一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆