1. Home
  2. Docs
  3. Simpods MVC
  4. Tutorials
  5. Views
  6. Access Variables From Controllers

Access Variables From Controllers

The MVC structure allows you to move your logic code away from the presentation code that produces your page. This helps clean up your template and focus purely on the layout. When you process data in the Controller, you will often want to pass the results through into the view so that it can be displayed on the page. To do this, follow the guide below.

Declaring a variable in the controller

To pass information through from the controller, the data must be in the global scope of the controller. To do this, declare a public variable before the __construct() function. For example:

Copy to Clipboard

In this example, a variable called $my_variable is available throughout the controller.

Putting data into the variable

Next, you will want to actually put some data into the variable.  As it is globally available across the whole file, you can use $this->[variable_name] to access the variable. As an example, let’s put some text into the string.

Copy to Clipboard

The variable now contains the string ‘Hello World!’

Accessing this variable in the frontend

The controller is globalised automatically, you can access it on the page as $ctrl. To access your custom variable, use $ctrl->[variable_name]. You can use this within the code or assign this to a variable for use later. For example:

Copy to Clipboard

This will produce a paragraph with the text ‘Hello World!’

Copy to Clipboard