How to access a variable in a PHP class that is set by another function? Codeigniter
我在 PHP 中使用 Codeigniter 框架有这段代码,我似乎无法理解这段代码中的类变量似乎与 C 完全不同。
我想知道如何将一个类(函数)方法中的局部变量传递给另一个类方法。
但没有将它们作为变量传递,因为我必须使用重定向函数而不是不能接受变量。
我想要访问的变量是 $record_id ,我尝试将其公开等不喜欢它。
class Submit 扩展了 CI_Controller
{
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function send_data() { $record_id = $this->submit_model->create_record($completedstaffrows, $completedeventrows); if ($record_id == FALSE) { echo"Failed to add to database"; } //Submittal to database was successful else { redirect('submit/success'); } return; } |
这是我想要访问 $record_id
的函数
1 2 3 4 5 6 7 8 9 | public function success() { $page['page'] = 'success'; $page['record'] = $record_id; $this->load->view('template', $page ); } |
记住——我不能把它作为一个变量传递给另一个函数,因为我需要使用重定向,这样我的 URL 就不会搞砸了。谢谢
干杯!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | class Submit extends CI_Controller { private $record_id=false; public function __construct(){ if(isset($_SESSION['record_id'])){ $this->record_id = $_SESSION['record_id']; } } public function send_data(){ $this->record_id = $this->submit_model->create_record($completedstaffrows, $completedeventrows); $_SESSION['record_id'] = $this->record_id; if ($this->record_id == FALSE){ echo"Failed to add to database"; } else{ redirect('submit/success'); } return; } public function success(){ $page['page'] = 'success'; $page['record'] = $this->record_id; $this->load->view('template', $page ); } } |
使用名为 Flashdata 的 codeigniter 小功能,它允许您在请求之间临时存储数据。
所以你的代码是
1 2 3 4 5 6 7 | function send data{ $this->session->set_flashdata('recordid', $recordid); } function success{ $recordid = $this->session->flashdata('recordid'); } |
知道了吗?