2015-12-10 92 views
0

爲什麼這個代碼給出未定義的變量:我在上面定義的變量爲$category_id; $ CATEGORY_IDPHP - 未定義的變量,雖然該變量是全局定義

// declare a variable and an array 
$category_id; 
$posts = []; 

// get four categories 
$categories = Category::take(4)->get(); 

foreach($categories as $category){ 
    //foreach of the four categories, get the category id 
    $category_id = $category->$category_id; 

    //add three posts of each of those categories to the $posts array 
    $posts[] = Category::where('category_id', $category_id)->take(3)->get(); 

} 

Althought。爲什麼錯誤仍然存​​在?
這是否與$category->$category_id傾斜代碼有關?

+0

是... $ category_id基本上是空的。沒有值。 – Daniel

+0

$ category - > $ category_id;有一個值,但錯誤在「$ category_id =」s $ category_id。這是爲什麼? –

+0

在哪一行上面出現錯誤!!,代碼 – sanjeev

回答

3
$category_id = $category->$category_id; 

是最有可能錯了,你可能意味着

$category_id = $category->category_id; 

,你應該(再次:最有可能的)一個通過賦予文本值初始化變量或常量或類似的,例如

// declare a variable and an array 
$category_id=null; 

(編輯:或離開初始化了完全的代碼片段你張貼,$ CATEGORY_ID只是用來當它顯然已經在循環中分配一個值,它看起來像您不保留在foreach循環後使用的變量。)

+0

謝謝:)它幫助。 –

0

我從來沒有聲明一個變量沒有任何類似於你之前的任何東西。

怎麼樣:

$category_id = null; 
+0

我想解釋爲什麼會發生這種情況。 –

+0

我不確定通過寫下它的名字來聲明一個變量是否合法? – SIDU

+0

「$ category_id = null;」 - 但是接下來'$ category - > {null}'是什麼? – VolkerK

0
<form method="post" action="convert1.php"> 
hour : <input type="hour" name="fhour"><br><br> 
minute:<input type="minute" name="fminute"><br><br> 
second: <input type="second" name="fsecond"><br><br> 
month:<input type="text" name="fmonth"><br><br> 
day:<input type="day" name="fday"><br><br> 
year : <input type="text" name="fyear"><br><br> 
date : <input type="date" name="fdate"><br><br> 

<input type="submit" name="submit" value="submit" > 
</form> 


<?php 
if(isset($_POST['submit'])) 
    //print_r($_POST); 
{ 



    $hour=$_REQUEST['fhour']; 
    $minute=$_REQUEST['fminute']; 
    $second=$_REQUEST['fsecond']; 
    $month=$_REQUEST['fmonth']; 
    $day=$_REQUEST['fday']; 
    $year=$_REQUEST['fyear']; 
    $date=$_REQUEST['fdate']; 

    $timestamp = mktime($fhour, $minute, $second, $month, $day, $year,$date); 
    //date('r', $timestamp); 
    echo 'timestamp in second='.$timestamp; 
    echo $minute=$timestamp/60; 
    echo '<br>'; 
    echo $second=$timestamp/24; 
    echo'<br>'; 
    echo $milisecond=$timestamp*100; 
    echo '<br>'; 

} 
?> 
please solution