在 Codeigniter Controller 中声明私有变量
Declaring private variable in Codeigniter Controller
我是 CI 的新手,我试图通过应用程序访问私有变量,但我为该变量设置了一个值,下次我尝试访问该函数(我调用从我看来的提交表单),我设置的私有变量是空的。有人可以帮忙吗?谢谢
class Example extends CI_Controller{
private $_variable;
public function __construct()
{
parent::__construct();
}
public function index()
{
//value from database
$this->_variable = 'somevalue';
}
//calling this function from a view
public function some_method()
{
// code...
// $this->_variable returning without any value
}
}
您的 some_method
实际上不是视图。充其量它可能是一个将从视图调用的示例控制器函数。你的index()
函数实际上是在你的私有$_variable
中赋值,所以要将值传递给你的视图,你必须先调用index()
函数赋值变量,这个值才会可用给你的some_method()
。下面给出了如何将变量传递给视图的示例。
public function some_method()
{
return $this->_variable;
}
在您看来,要访问变量:
echo $this->some_method();
我相信这会帮助您在您的视图中显示您的私有变量。
您的视图不应直接尝试访问控制器的方法,相反,您应该在第二个参数中调用视图时发送这些方法:
See Codeigniter's docs related to this(我假设你是西班牙人,因为你使用 "variable")。
$args = Array( "var1" => "variable", "var2" => "variable" );
$this->load->view("some_url", $args);
然后 $var1 和 $var2 将在您的视图中可用。
我是 CI 的新手,我试图通过应用程序访问私有变量,但我为该变量设置了一个值,下次我尝试访问该函数(我调用从我看来的提交表单),我设置的私有变量是空的。有人可以帮忙吗?谢谢
class Example extends CI_Controller{
private $_variable;
public function __construct()
{
parent::__construct();
}
public function index()
{
//value from database
$this->_variable = 'somevalue';
}
//calling this function from a view
public function some_method()
{
// code...
// $this->_variable returning without any value
}
}
您的 some_method
实际上不是视图。充其量它可能是一个将从视图调用的示例控制器函数。你的index()
函数实际上是在你的私有$_variable
中赋值,所以要将值传递给你的视图,你必须先调用index()
函数赋值变量,这个值才会可用给你的some_method()
。下面给出了如何将变量传递给视图的示例。
public function some_method()
{
return $this->_variable;
}
在您看来,要访问变量:
echo $this->some_method();
我相信这会帮助您在您的视图中显示您的私有变量。
您的视图不应直接尝试访问控制器的方法,相反,您应该在第二个参数中调用视图时发送这些方法:
See Codeigniter's docs related to this(我假设你是西班牙人,因为你使用 "variable")。
$args = Array( "var1" => "variable", "var2" => "variable" );
$this->load->view("some_url", $args);
然后 $var1 和 $var2 将在您的视图中可用。