3

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

3 Answers 3

4

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);
  }

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

1 Comment

As noted below, "defining a property in the controller is not persistent after subsequent calls to the controller."
2

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.

Comments

1

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...

Comments

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.