views:

27

answers:

2

I'm new to CakePHP and I'm looking at some code I've downloaded that has a function that looks like this:

$this->set(array('fruit' => 'orange', 'vegetable' => 'kale'));

In the code, the array variables are accessed in another controller function using this method:

$varsSet = $this->viewVars;
echo $varsSet['vegetable'];

What I'd like to do access the array variables in the same function in the controller where the $this-set() statement is made, and it seems like I should be able to do so with just one line of code. I've tried all of the following:

echo $fruit;
echo $this->field('fruit');
echo $this->MyModel->$fruit;
echo $this->MyModel->field('fruit');

And all of these throw parse, undefined variable, or variable not found errors. What would be the simplest/most proper way to access the variable within the same function in the controller?

Thanks,

Jonathan

+1  A: 

Function $this->set() in the controller is used to pass variables from the controller to the view.

I.e.

If you have:

$this->set('fruit' => array('orange', 'vegetable' => 'kale'));

Then in the associated view you can access the array directly as

print_r($fruit);

If you want to use fruit variable in the controller, then you have to assign it to the var i.e.:

$fruits = array('orange', 'vegetable' => 'kale');
$this->set('fruit' => $fruits);

But your question is not very clear what do you want to achieve with this.

Nik
Sorry for the confusion...I was wondering if I just needed to create the variable then use it as needed in the controller and pass it to $this-set(), and this answers my question, thanks!
Jonathan
A: 

I think this is what you are looking for:

$this->set('fruit', 'orange');
$this->set('vegetable', 'kale');

And then in the view, you can reference:

$fruit
$vegetable
cdburgess