PHP - 未定义的变量,尽管变量是全局定义的

时间:2015-12-10 05:46:49

标签: php laravel variables

为什么此代码会提供未定义变量:$ category_id

// 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();

}

虽然我将顶部的变量定义为$category_id;。为什么错误仍然存​​在?
是否与$category->$category_id倾斜代码有关?

3 个答案:

答案 0 :(得分:3)

$category_id = $category->$category_id;

很可能是错的,你可能意味着

$category_id = $category->category_id;

你应该(再次:最有可能)通过指定一个文字值或常数或类似值来初始化变量,例如

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

(编辑:或将 初始化完全保留。在您发布的代码段中,$ category_id仅在明显分配了值时使用循环,看起来你没有保留变量以便在foreach循环之后使用。)

答案 1 :(得分:0)

我从来没有声明变量,没有任何跟随你之前的事情。

怎么样:

$category_id = null;

答案 2 :(得分: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