CodeIgniter控制器未将信息传递给模型

时间:2014-07-25 00:19:51

标签: php codeigniter templates

我正在关注一个例子的细节。我不确定问题是什么,当我将php从视图中移出视图时,控制器将标题传递给视图。但是当我将简单的数学问题添加回视图主体时,控制器似乎没有将此信息传递到模型中。我在这里做错了什么?

模型math.php

<?php

class Math extends CI_Model {

    public function add($var1, $var2)
    {
        return $var1+ $var2;
    }

    public function subtract($var1, $var2)
    {
        return $var2 - $var1;
    }

}

Controller site.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Site extends CI_Controller {

    public function index()
    {
        echo "Hello World<br>";
        $this->home();
    }

    public function home()
    {
        $data['title'] = 'Welcome!';
        $data['var1'] = 2;
        $data['var2'] = 5;

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

        $data['addTotal'] = $this->math->add($data['var1'], $data['var2']);
        $data['subTotal'] = $this->math->subtract($data['var1'], $data['var2']);

        $this->load->view('home', $data);
    }

}

查看home.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>

</head>
<body>

<div id="container">

<h3>Add</h3>
<p><?php echo $var1 . " + " . $var2 " = " $addTotal; ?></p>

<h3>Subtract</h3>
<p><?php echo $var2 . " - " . $var1 " = " $subTotal; ?></p>

</div>

</body>
</html>

3 个答案:

答案 0 :(得分:1)

我得到了输出......

Hello World

添加

2 + 5 = 7

减去

5 - 2 = 3

你忘了 concat “=”

<h3>Add</h3>
<p><?php echo $var1 . " + " . $var2 " = " $addTotal; ?></p>

<h3>Subtract</h3>
<p><?php echo $var2 . " - " . $var1 " = " $subTotal; ?></p>

应该......

<h3>Add</h3>
<p><?php echo $var1 . " + " . $var2 . " = " . $addTotal; ?></p>

<h3>Subtract</h3>
<p><?php echo $var2 . " - " . $var1.  " = " . $subTotal; ?></p>

答案 1 :(得分:0)

试试这个,这可能有所帮助。

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

        class Site extends CI_Controller {

            public function __construct()
            {
              parent::__construct();       
              $this->load->model('math');

            }
            public function index()
            {
                echo "Hello World<br>";
                $this->home();
            }

            public function home()
            {
                $data['title'] = 'Welcome!';
                $data['var1'] = 2;
                $data['var2'] = 5;
                $data['addTotal'] = $this->math->add($data['var1'], $data['var2']);
                $data['subTotal'] = $this->math->subtract($data['var1'], $data['var2']);

                $this->load->view('home', $data);
            }

        }

编辑:

要打开错误报告,请转到ci中的主index.php文件,该文件与应用程序文件夹位于同一目录中,并确保将环境设置为开发

define('ENVIRONMENT', 'development');

答案 2 :(得分:0)

试试这个,它会正常工作。

    <div id="container">
       <h3>Add</h3>
       <p><?php echo $var1+$var2; ?></p>
       <h3>Subtract</h3>
       <p><?php echo $var2-$var1; ?></p>
    </div>