【问题标题】:Variable value in codeigniter viewscodeigniter 视图中的变量值
【发布时间】:2013-01-31 11:18:38
【问题描述】:

我正在尝试将变量从控制器传递到视图。我有一些代码,但为了理解问题是什么,我把它简单化了。这是我的控制器:

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

    class Welcome extends CI_Controller {

        $p=2;

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

?>

在视图中声明了变量 p。

<div id="container">
    <h1>Welcome to CodeIgniter!</h1>
    <?php echo $p?>
</div>

当我尝试显示 $p 值时,我得到了错误:

错误

Parse error: syntax error, unexpected '$p' (T_VARIABLE), expecting function (T_FUNCTION) in C:\wamp\www\..\application\controllers\welcome.php on line 20

怎么了?

谢谢。

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

    第一个变量需要作为数组传递 (check out the docs)。

    $data = array(
                   'title' => 'My Title',
                   'heading' => 'My Heading',
                   'message' => 'My Message'
              );
    
    $this->load->view('welcome_message', $data);
    

    $p 已被声明超出函数的范围,所以要么;

    public function index() {
       $p = 2;
       $this->load->view('welcome_message',array('p' => $p));
    }
    

    class Welcome extends CI_Controller {
    
    public $p=2;
    
    public function index()
    {
        $this->load->view('welcome_message',array('p' => $this->p));
    }
    }
    

    【讨论】:

    • 是的。现在可以了。但是当我更改我的真实代码时,我遇到了另一个错误:遇到了 PHP 错误 严重性:通知消息:未定义的属性:CI_Loader::$arrPermisos 文件名:marketing/campanas.php 行号:6 控制器代码:public function index() { $this-&gt;load-&gt;view("marketing/campanas",$this-&gt;arrPermisos); }查看代码:&lt;ul class="menuArea"&gt; &lt;?php if ($this-&gt;arrPermisos["campanas_leer"]) { ?&gt; &lt;li class="current"&gt;&lt;a href="/comercial/campanas/"&gt;Campañas&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; 怎么了?
    • @axmug 是 $this->arrPermisos 哈希数组吗?
    • 是的。它是一个保存角色用户的数组。
    • 在视图代码中引用时需要使用数组元素的key作为变量。例如,在控制器数组中('foo' => 1),然后当传递到您的视图时,通过 $foo 访问它
    • 是的。我试过了,但它不起作用。我不知道为什么。如果我输入:&lt;?php if ($arrPermisos["campanas_leer"]) { ?&gt; &lt;li class="current"&gt;&lt;a href="/comercial/campanas/"&gt;Campañas&lt;/a&gt;&lt;/li&gt; &lt;?php } 错误是未定义的变量 arrPermisos。
    【解决方案2】:

    您应该在控制器的构造函数中声明$p

    class Welcome extends CI_Controller {
    
        function __construct() {
        parent::__construct();
            $this->p = 2;
        }
    
        public function index()
        {
            $data['p'] = $this->p;
            $this->load->view('welcome_message',$data);
        }
    }
    

    ?>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-24
      • 2011-02-07
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2016-01-10
      相关资源
      最近更新 更多