0

this is my first post.

I'm new to Yii framework.

I'm having a problem now with rendering view. I get an undefined variable error when I render Controller.

I don't understand why I get an undefined variable error although the variable getting error is surrounded with if statement.

the code below is what I simplified my code that I'm actually working on.

Please help me out! I'd like to know the reason why Im getting an undefined variable error and also I'd like to know how to solve this problem.

Thanks very much in advance!!!

+++ Controller +++

class CategoryController extends Controller
{

    public function actionIndex()
    {

        $flag = false;

            if($flag){

                $this->render('index', array('test'=>$flag));

            }


        //This causes "Undefined variable:test" Error.
        $this->render('index');

        //This works fine.
        //$this->render('index', array('test'=>$flag));

    }


}

+++ View(this is rendered with layout view. +++

<?php 
if($test){ 
    echo "$test is false";
}else{
    echo "$test is true";
}
?>
3
  • Because if($test) still requires a variable to be defined. If you want to test if a variable exists, use if(isset($test)). Commented Aug 9, 2013 at 8:51
  • shouldn't it be something like $this->test Commented Aug 9, 2013 at 8:57
  • >DCoder Thanks, it works!! Commented Aug 9, 2013 at 9:23

1 Answer 1

2

It's a fact that you receive an error since attempts to access a $test in your View without passing it through the Controllers render is wrong.

You'd pass varible with the rendering function all the time or just check if it is set if(isset($test)) in your View file.

Cheers!

Sign up to request clarification or add additional context in comments.

2 Comments

<?php if(isset($test)){ echo "$test is false"; }else{ echo "$test is true"; } ?>
But when you write a $variable between doble "", PHP evaluates this variable. And in 'else' when you print: echo "$test is true"; the php displays the value of the variable. Put this between '$test is true' simple.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.