所以我认为我有这个 IF 语句。它有效,但想知道是否有更好的方法来写这个。有两个会话调用似乎没有必要......
if($this->session->userdata('campaign_name')){
echo $this->session->userdata('campaign_name');
}
else {
echo 'this';
}
请注意,此函数将在文本输入中内联使用。所以我正在寻找尽可能少的代码。
所以我认为我有这个 IF 语句。它有效,但想知道是否有更好的方法来写这个。有两个会话调用似乎没有必要......
if($this->session->userdata('campaign_name')){
echo $this->session->userdata('campaign_name');
}
else {
echo 'this';
}
请注意,此函数将在文本输入中内联使用。所以我正在寻找尽可能少的代码。
请注意,如果不campaign_name
存在,CI 的 Session 类的 userdata 方法将返回 false。因此将一个变量分配给可能未定义的数组键(campaign_name)
$campaign_name = $this->session->userdata('campaign_name');
if($campaign_name)
{
echo $campaign_name;
}
else
{
echo 'this';
}
或者
if($campaign_name = $this->session->userdata('campaign_name'))
{
echo $campaign_name;
}
控制器方法(/application/controllers/test_controller.php)
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Test_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function myFunction()
{
$data['campaign_name'] = $this->session->userdata('campaign_name');
$this->load->view('test_view',$data);
}
}
查看(/application/view/test_view.php)
<html>
<head></head>
<body>
<input type="text" value="<?php echo $campaign_name; ?>">
</body>
</html>
In your controller, you can store the value of that session data into a variable and pass that along to the view. In the view, you can then have your if else statements that just look at the variable. I would advise against setting a variable in the view as RPM did. While it works, it breaks the separation of concerns you have going.
Also, look into using the alternative PHP syntax for views in CodeIgniter. It'll make your code neater and more maintainable.
Edit: I see now that RPM has updated his answer to set the variable in the controller. That's a good example to follow.