【问题标题】:codeigniter global variable value not accessablecodeigniter 全局变量值不可访问
【发布时间】:2016-06-22 10:42:22
【问题描述】:

我在控制器内定义了全局变量,但我在 index() 函数内赋值。值可以在 index() 内部访问,但不能在 about 和其他函数内部访问。我该怎么做 ??

class Manage_business extends CI_Controller
    {
    var $id;

    public function __construct()
    {
        parent::__construct();  
    }

    public function index($no)
    {

        $this->id=$no;
        echo $this->id;
    }

    public function about()
    {
        echo $this->id;
        die();
}
}

【问题讨论】:

  • 构造函数内部有赋值。我在 index() 内部分配。即使我不想要超级全局变量。
  • 如果您直接使用 about 函数,那么您无法通过 index 函数设置 $this->id 的值,因为它从未被调用过。
  • 拳头我的索引函数调用。之后其他人。
  • 你可以像$this->about($no)在索引函数中调用一样传递它

标签: php codeigniter


【解决方案1】:

尝试使用会话,这是您拥有的众多选项之一

class Manage_business extends CI_Controller {

public function __construct()
{
    parent::__construct(); 
    $this->load->library('session);
}

public function index($no)
{
    $this->session->set_userdata('id',$no) //to last
    $this->session->set_flashdata('id',$no) //available only for the next refresh
    echo $this->id;
}

public function about()
{
    echo $this->session->id;
    die();

} }

这样你就可以在索引上看到你做了什么,请看看它对你有用,还有其他方法,但我认为这个是最有效和最容易使用的。

【讨论】:

  • @wolfgang1983 是的,但就是我上面写的,他正在尝试填充一个全局变量,但使用不同的方法,为了调用这些方法,我猜他正在刷新页面,为此,他需要会话或任何将他的数据保存在控制器中的东西
【解决方案2】:

codeigniter 不允许使用此方法,因为您应该使用 in 控制器或 modal 定义值,然后将它们转发到 .最简单的方法之一是在 config/constants.php 中定义为常量,这将在整个应用程序中可用,而无需传递给模式或视图或控制器,它们将可在任何地方全局访问.. 另一种方法是在 cisession 中使用会话值必须调用会话并提取值。

【讨论】:

    【解决方案3】:

    您在变量声明中使用了 var,这会产生语法错误。可以在construct() 中创建全局变量,以便类中的其他函数可以使用该变量。

    请检查下面的更正代码。

    class Manage_business extends CI_Controller
    {
    
    
    public function __construct()
    {
        parent::__construct(); 
        $id;        
    }
    
    public function index($no)
    {
    
        $this->id=$no;
        echo $this->id;
    }
    
    public function about()
    {
        echo $this->id;
        die();
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多