2013-01-31 65 views
3

我想将一个变量从控制器传递给视图。我有一些代码,但为了理解我简化了什么问题。这里是我的控制器:在codeigniter视图中的变量值

<?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 

有什么不对?

谢谢。

回答

0

你应该在你的控制器的构造函数声明$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); 
    } 
} 

>

3

的第一变量需要作为一个数组(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)); 
} 
} 
+0

是。它现在有效。但是,当我在实际的代码改变了我有另一个错误: 一个PHP错误遇到 严重性:注意 消息:未定义的属性:CI_Loader :: $ arrPermisos 文件名:市场营销/ campanas.php 行号:6 控制器代码:'公共功能索引() \t {$ this-> load-> view(“marketing/campanas”,$ this-> arrPermisos); }'视图代码:' \t \t \t \t \t \t <(arrPermisos [ “campanas_leer”] {> \t \t \t \t \t \t

  • ?类= “当前”>Campañas
  • \t \t \t \t \t \t \t \t \t \t \t'什么是WR翁? – axmug

    +0

    @axmug是$ this-> arrPermisos一个哈希数组? – Rooneyl

    +0

    是的。这是保存用户角色的阵列。 – axmug

    相关问题