可能重複:
PHP: 「Notice: Undefined variable」 and 「Notice: Undefined index」發送變量到視圖從控制器蛋糕不工作
在我的意見控制器,我有以下方法:
public function popularTabs() {
$this->set('hour', $this->popularToday()); // send hour
$this->set('today', $this->popularHour()); // send day
}
我打算將變量'hour'和'today'發送到視圖。這些都發送一個數組,其中包含來自popularToday()和popularHour()方法的數據,這些數據在私有方法中定義在同一個控制器中。它們看起來像:
private function popularHour() {
return $submissions = $this->Submission->find('all', array(
'conditions' => array('Submission.approved' => '1'),
'order' => 'Submission.created DESC'
));
}
裏面我認爲,所謂的popular.ctp的,我做了檢查,看是否參數包含小時或今天,並顯示相應的數據通過調用它基本上只是格式元素它符合我的喜好(元素在其他地方正確顯示,所以沒有問題)。
該視圖(popular_tabs.ctp)的代碼是:
if ($this->params['pass'][0] == 'hour') {
// Set our $hour variable to $submissions, which is what the
// foreach loop inside single_submission_entry uses as a variable
// to loop through
$submissions = $hour;
echo $this->element('single_submission_entry', $hour);
}
if ($this->params['pass'][0] == 'today') {
$submissions = $hour;
echo $this->element('single_submission_entry', $today);
}
出於某種原因,雖然,除非在popularTabs()
方法中,如果我的變量設置爲任何大於提交例如OTHER
$this->set('submissions', $this->popularToday()); // send hour
它將無法正確顯示。如果我嘗試設置變量來小時,還是今天,它會給我下面的輸出:
Notice (8): Undefined variable: submissions [APP/views/elements/single_submission_entry.ctp, line 1]
Warning (2): Invalid argument supplied for foreach() [APP/views/elements/single_submission_entry.ctp, line 1]
線single_submission_entry
1:
<? foreach ($submissions as $count => $submission): ?>
// display submission stuff here
<? endforeach; ?>
其中我特別是將$小時重命名爲$提交...所以我不確定我在這裏錯過了什麼?
如果我從我的視圖(popular_tabs.ctp)內部輸入print_r($ hour),它會發送正確的數據,爲什麼它沒有正確發送到single_submission_entry?
哇。這讓我瘋狂。非常感謝! – 2012-02-05 05:32:10
不客氣!第二個參數基本上作爲元素的'this-> set()'。 – 2012-02-05 05:34:35