为什么我在Yii控制器中得到未定义的变量错误?

时间:2014-05-09 11:38:07

标签: php yii

我的控制器出现Undefined variable: user错误:

这是我的控制器

public function actionduration()
{
    if (isset($_POST['W'])&&isset($_POST['Nodelist']))
    {
        $user = Sensor::model()->Week();
    }
    else if (isset($_POST['M'])&&isset($_POST['Nodelist']))
    {
        $user = Sensor::model()->Month();
    }
    else if(isset($_POST['S'])&&isset($_POST['Nodelist']))
    {
        $user = Sensor::model()->Six();
    }
    else if(isset($_POST['Y'])&&isset($_POST['Nodelist']))
    {
        $user = Sensor::model()->Year();
    }
    //print_r($user);

    $this->layout='main2';
    //$layout='//layouts/main1';
    $this->render('edit1', array('user'=>$user));
}

2 个答案:

答案 0 :(得分:1)

在启动时声明$user。因为你的$ user没有在任何if else语句中设置。

试试这个:

public function actionduration()
{
  $user=""; 
  $this->layout='main2';
 if (isset($_POST['W'])&&isset($_POST['Nodelist']))
  {
    $user = Sensor::model()->Week();
   }
else if (isset($_POST['M'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Month();
}
else if(isset($_POST['S'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Six();
}
else if(isset($_POST['Y'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Year();
}

$this->render('edit1', array('user'=>$user));
}

或者您可以在最后创建另外一个:

public function actionduration()
{
if (isset($_POST['W'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Week();
}
else if (isset($_POST['M'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Month();
}
else if(isset($_POST['S'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Six();
}
else if(isset($_POST['Y'])&&isset($_POST['Nodelist']))
{
    $user = Sensor::model()->Year();
}
else
{
   $user=""; 
 }
//print_r($user);

$this->layout='main2';
//$layout='//layouts/main1';
$this->render('edit1', array('user'=>$user));
}

答案 1 :(得分:0)

这意味着您的代码未初始化$ user。进行测试以检查是否有任何if条件返回true。看起来他们都回归假。