tags:

views:

726

answers:

3

Hi,

I would like to pass a variable from one controller function to an other. In other words, how can I access the variable from an other function, within the same controller?

Thanks

+1  A: 

Consdidering your Controllers are classes, you have two solutions :

  • pass the variable as a parameter from one method to the other ; see Function arguments
  • or store the data in a class-property, visible from all methods in the same class ; see Properties

Which one of those solutions should you use ?

I suppose it depends on the situation :

  • If you only have a few data to share between only two methods, passing them as parameters is probably the way to go.
  • If you have data that should be shared by all methods, the second one is the right solution.
  • If you are between those two cases... You'll probably have to judge by yourself which one is the most practical solution...
Pascal MARTIN
+2  A: 

As Pascal mentioned, one way is to set a property on the object:

class CategoriesController extends AppController
{

  public $foo = '';  

  public function index()
  {
    $this->foo = 'bar';
  }

  public function view($id = null)
  {
    $baz = $this->foo;

    $this->set('baz', $baz);
  }

}

Or pass it as argument:

class CategoriesController extends AppController
{

  public function index()
  {
    $foo = "bar";
    $this->view($foo)
  }

  public function view($param)
  {
    $this->set('bar', $param);
  }

}
Darren Newton
A: 

I noticed that defining a property in the controller is not persistent after subsequent calls to the controller.

However, defining a property in the model is persistent between controller function calls.

Michael